@asstio-dev/storefront 0.47.0 → 0.48.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 CHANGED
@@ -789,12 +789,13 @@ export async function beginSignedInCheckout(savedCart: string) {
789
789
  }
790
790
  ```
791
791
 
792
- ### Favorites and consent
792
+ ### Favorites, stock watches and consent
793
793
 
794
- Guest favorites and the device's consent live in four entries (shopper-state spec):
794
+ Guest favorites, stock watches and the device's consent live in five entries (shopper-state spec):
795
795
 
796
- - `@asstio-dev/storefront/account/next` — `shopperActions(config)`: favorites, the shopper's own state (read, erase),
797
- consent (read, history, put) and `adopt()`. Signed in they use `/v1/me/*`, as a guest the `/v1/shopper/*` relay. A
796
+ - `@asstio-dev/storefront/account/next` — `shopperActions(config)`: favorites, stock watches (`watches.create`, `list`,
797
+ `cancel(id)`, `stopAll()` — the last one signed in only), the shopper's own state (read, erase), consent (read, history,
798
+ put) and `adopt()`. Signed in they use `/v1/me/*`, as a guest the `/v1/shopper/*` relay. A
798
799
  guest's first write mints a shopper token into the HttpOnly `__Host-sf_shopper` cookie; no result ever carries it.
799
800
  Node runtime only: the module loads `node:crypto`.
800
801
  - `@asstio-dev/storefront/account/browser` — `withShopperLock(actions)`: wrap your `"use server"` shopper actions in
@@ -807,6 +808,12 @@ Guest favorites and the device's consent live in four entries (shopper-state spe
807
808
  `{ put: locked.consent.put }`. Gate every measurement or personalization on `coordinator.effective()`.
808
809
  - `@asstio-dev/storefront/consent/server` — `readConsentCookie(cookies)` (the same answer for SSR) and
809
810
  `consentOwner(cookies, session)`.
811
+ - `@asstio-dev/storefront/shopper` — the watch types `ShopperWatch` (owner projection) and `RecipientWatch`, the union
812
+ `Watch` narrowed by `projection`, and `cancelWatchByToken(client, token, "watch" | "all", { shopperIp? })` for the mail's
813
+ cancel page. In the browser pass the publishable-key client from `createStorefrontClient`; on the server pass a
814
+ server-key client and the shopper's IP (`createShopperClient({ serverKey, shopperIp })`, or `{ shopperIp }` here), so the
815
+ rate limit is the shopper's and never one bucket for everyone behind your server. It never sends a session or shopper
816
+ token, and the API answers `204` whatever the token is, so show a fixed text.
810
817
 
811
818
  ## Headers
812
819
 
@@ -2,6 +2,7 @@ import { type AccountResult, type PrincipalDto, type ShopperClient } from "./ind
2
2
  import type { components } from "../schema";
3
3
  import type { CommerceContextOptions } from "../context.js";
4
4
  import { type CopyBrowserCartResult } from "./cart.js";
5
+ import type { CreateWatchInput, WatchAnswer, WatchList } from "../shopper/index.js";
5
6
  export type AccountActionConfig = {
6
7
  /** e.g. https://api.storefront.asstio.com */
7
8
  baseUrl: string;
@@ -135,7 +136,7 @@ export type ShopperStateView = ShopperStateDto | {
135
136
  shopper: null;
136
137
  };
137
138
  /**
138
- * Server actions for favorites, the shopper's own state and consent (shopper-state spec §4.2, §5, §7.4, §9.4; PL8, PL9). Call them
139
+ * Server actions for favorites, stock watches, the shopper's own state and consent (shopper-state spec §4.2, §5, §6, §7.4, §9.4; PL8, PL9). Call them
139
140
  * from your own `"use server"` actions. Signed in (a session cookie) they use `/v1/me/*`; as a guest the session-less `/v1/shopper/*`
140
141
  * relay with the server key and `X-Shopper-Ip`. The guest token lives only in `__Host-sf_shopper` (HttpOnly, 12 months): a minting
141
142
  * answer sets it, every other successful guest write renews it, `SHOPPER_TOKEN_UNKNOWN`/`SHOPPER_TOKEN_ADOPTED` clear it, and no
@@ -152,6 +153,25 @@ export declare function shopperActions(config: AccountActionConfig): {
152
153
  /** `DELETE …/favorites`; a guest without a token has nothing to clear (no request). */
153
154
  clear(): Promise<AccountResult<void>>;
154
155
  };
156
+ watches: {
157
+ /**
158
+ * `POST /v1/me/watches` signed in (addressed to the account's own e-mail: `email` is not sent), `POST /v1/shopper/watches` as a
159
+ * guest with `email` (a watch asks for a service, so without a token this mints one: persisted in the cookie, never returned).
160
+ * `201` for a new watch, `200` for the caller's open one; `WATCH_NOT_NEEDED` (`409`) means offer add to cart instead.
161
+ */
162
+ create(input: CreateWatchInput): Promise<ShopperActionResult<WatchAnswer>>;
163
+ /** `GET /v1/me/watches` signed in (recipient or owner projection per watch); `GET /v1/shopper/watches` as a guest (owner
164
+ * projection; no token: an empty list, no request). */
165
+ list(): Promise<AccountResult<WatchList>>;
166
+ /** `DELETE …/watches/{id}` (`204` whether or not there is such a watch); a guest without a token has nothing to cancel (no request). */
167
+ cancel(id: string): Promise<AccountResult<void>>;
168
+ /**
169
+ * `POST /v1/me/watches/stop-all`: stop every watch addressed to the account's own e-mail and watch mail to it for 12 months.
170
+ * Session only (signed out: `SESSION_REQUIRED`, no request). The mail's cancel link is `cancelWatchByToken` in
171
+ * `@asstio-dev/storefront/shopper`, with the publishable key: these actions hold the server key.
172
+ */
173
+ stopAll(): Promise<AccountResult<void>>;
174
+ };
155
175
  shopperState: {
156
176
  /**
157
177
  * `GET /v1/shopper` with the token, **always on the guest route and without the session** (the "keep my list" prompt reads it
@@ -224,7 +224,7 @@ function guestVoid(ctx, r) {
224
224
  return r;
225
225
  }
226
226
  /**
227
- * Server actions for favorites, the shopper's own state and consent (shopper-state spec §4.2, §5, §7.4, §9.4; PL8, PL9). Call them
227
+ * Server actions for favorites, stock watches, the shopper's own state and consent (shopper-state spec §4.2, §5, §6, §7.4, §9.4; PL8, PL9). Call them
228
228
  * from your own `"use server"` actions. Signed in (a session cookie) they use `/v1/me/*`; as a guest the session-less `/v1/shopper/*`
229
229
  * relay with the server key and `X-Shopper-Ip`. The guest token lives only in `__Host-sf_shopper` (HttpOnly, 12 months): a minting
230
230
  * answer sets it, every other successful guest write renews it, `SHOPPER_TOKEN_UNKNOWN`/`SHOPPER_TOKEN_ADOPTED` clear it, and no
@@ -275,6 +275,59 @@ export function shopperActions(config) {
275
275
  return guestVoid(ctx, voidResult(await ctx.client(null).DELETE("/v1/shopper/favorites", { headers: tokenHeader(ctx.token) })));
276
276
  },
277
277
  },
278
+ watches: {
279
+ /**
280
+ * `POST /v1/me/watches` signed in (addressed to the account's own e-mail: `email` is not sent), `POST /v1/shopper/watches` as a
281
+ * guest with `email` (a watch asks for a service, so without a token this mints one: persisted in the cookie, never returned).
282
+ * `201` for a new watch, `200` for the caller's open one; `WATCH_NOT_NEEDED` (`409`) means offer add to cart instead.
283
+ */
284
+ async create(input) {
285
+ const ctx = await shopperContext(config);
286
+ const target = { kind: "variant", productId: input.productId, variantId: input.variantId };
287
+ const common = { kind: "stock", target, language: input.language ?? null, source: input.source ?? null };
288
+ if (ctx.session) {
289
+ const client = ctx.client(ctx.session);
290
+ const [r, me] = await Promise.all([client.POST("/v1/me/watches", { body: common }), getMe(client)]);
291
+ return accountView(accountResult(r), me);
292
+ }
293
+ const body = { ...common, email: input.email ?? null };
294
+ const r = await ctx.client(null).POST("/v1/shopper/watches", { body, headers: tokenHeader(ctx.token) });
295
+ return guestView(ctx, accountResult(r), true);
296
+ },
297
+ /** `GET /v1/me/watches` signed in (recipient or owner projection per watch); `GET /v1/shopper/watches` as a guest (owner
298
+ * projection; no token: an empty list, no request). */
299
+ async list() {
300
+ const ctx = await shopperContext(config);
301
+ if (ctx.session)
302
+ return accountResult(await ctx.client(ctx.session).GET("/v1/me/watches"));
303
+ if (!ctx.token)
304
+ return { ok: true, data: { items: [] } };
305
+ const r = accountResult(await ctx.client(null).GET("/v1/shopper/watches", { headers: tokenHeader(ctx.token) }));
306
+ keepToken(ctx, r, false);
307
+ return r;
308
+ },
309
+ /** `DELETE …/watches/{id}` (`204` whether or not there is such a watch); a guest without a token has nothing to cancel (no request). */
310
+ async cancel(id) {
311
+ const ctx = await shopperContext(config);
312
+ const params = { path: { id } };
313
+ if (ctx.session)
314
+ return voidResult(await ctx.client(ctx.session).DELETE("/v1/me/watches/{id}", { params }));
315
+ if (!ctx.token)
316
+ return { ok: true, data: undefined };
317
+ return guestVoid(ctx, voidResult(await ctx.client(null).DELETE("/v1/shopper/watches/{id}", { params, headers: tokenHeader(ctx.token) })));
318
+ },
319
+ /**
320
+ * `POST /v1/me/watches/stop-all`: stop every watch addressed to the account's own e-mail and watch mail to it for 12 months.
321
+ * Session only (signed out: `SESSION_REQUIRED`, no request). The mail's cancel link is `cancelWatchByToken` in
322
+ * `@asstio-dev/storefront/shopper`, with the publishable key: these actions hold the server key.
323
+ */
324
+ async stopAll() {
325
+ const ctx = await shopperContext(config);
326
+ if (!ctx.session)
327
+ return localFailure("SESSION_REQUIRED", "Stopping all watches needs a signed-in shopper.");
328
+ return voidResult(await ctx.client(ctx.session).POST("/v1/me/watches/stop-all"));
329
+ },
330
+ },
278
331
  shopperState: {
279
332
  /**
280
333
  * `GET /v1/shopper` with the token, **always on the guest route and without the session** (the "keep my list" prompt reads it
@@ -2,7 +2,11 @@ import type { Client } from "openapi-fetch";
2
2
  import type { components } from "../schema";
3
3
  import type { StorefrontPaths } from "../index.js";
4
4
  type Schemas = components["schemas"];
5
- /** One search event. `eventId` may be left out: `trackSearchEvents` writes a UUID into the object. */
5
+ /**
6
+ * One search event. `eventId` may be left out: `trackSearchEvents` writes a UUID into the object. A rendered recommendation row
7
+ * (`type: "recommendation_exposure"`, shopper-state spec §9.2) carries `resultId` (32 hex), `productIds` and `placement`
8
+ * (`pdp.similar`, `cart.complements`; trimmed and lower-cased by `trackSearchEvents`, the server wants 1–64 of `[a-z0-9_.-]`).
9
+ */
6
10
  export type SearchEvent = Omit<Schemas["SearchEventDto"], "eventId"> & {
7
11
  eventId?: string | null;
8
12
  };
@@ -14,9 +14,12 @@ export async function trackSearchEvents(client, events, options) {
14
14
  return null;
15
15
  if (events.length > MAX_EVENTS_PER_REQUEST)
16
16
  throw new RangeError(`trackSearchEvents takes at most ${MAX_EVENTS_PER_REQUEST} events per call, got ${events.length}`);
17
- for (const e of events)
17
+ for (const e of events) {
18
18
  if (!e.eventId)
19
19
  e.eventId = crypto.randomUUID();
20
+ if (e.type === "recommendation_exposure" && typeof e.placement === "string")
21
+ e.placement = e.placement.trim().toLowerCase();
22
+ }
20
23
  const { data, error, response } = await client.POST("/v1/events", { body: { events: events } });
21
24
  // `error` is undefined for an empty-body 5xx (openapi-fetch parses nothing), so the status decides: a non-2xx always throws.
22
25
  if (!response.ok)
@@ -0,0 +1,38 @@
1
+ import type { Client } from "openapi-fetch";
2
+ import type { StorefrontPaths } from "./index.js";
3
+ import type { components } from "./schema";
4
+ import { type StorefrontProblem } from "./checkout/types.js";
5
+ export type CartDto = components["schemas"]["CartDto"];
6
+ export type CartLineDto = components["schemas"]["CartLineDto"];
7
+ export type CartLineSegmentDto = components["schemas"]["CartLineSegmentDto"];
8
+ export type PricePairDto = components["schemas"]["PricePairDto"];
9
+ export type CartCodeResult = {
10
+ ok: true;
11
+ data: CartDto;
12
+ } | {
13
+ ok: false;
14
+ status: number;
15
+ problem: StorefrontProblem;
16
+ retryAfter?: number;
17
+ };
18
+ export interface CartCodeOptions {
19
+ /** The cart version (ETag); a stale one is rejected with 409 CART_CONFLICT. */
20
+ ifMatch?: number;
21
+ /** Default: a fresh `crypto.randomUUID()` per call. */
22
+ idempotencyKey?: string;
23
+ /** A signed-in frontend's request-scoped shopper client; the call goes through it instead of `client`. */
24
+ shopper?: Client<StorefrontPaths> | null;
25
+ }
26
+ /** `POST /v1/cart/codes`: applies a discount code. A transport failure rejects the promise, like the checkout helpers. */
27
+ export declare function applyCode(client: Client<StorefrontPaths>, cartToken: string, code: string, opts?: CartCodeOptions): Promise<CartCodeResult>;
28
+ /** `DELETE /v1/cart/codes/{code}`: removes a discount code (the path segment is URL-encoded). */
29
+ export declare function removeCode(client: Client<StorefrontPaths>, cartToken: string, code: string, opts?: CartCodeOptions): Promise<CartCodeResult>;
30
+ export type LineUnitPrices = {
31
+ kind: "single";
32
+ unitPrice: PricePairDto;
33
+ } | {
34
+ kind: "segments";
35
+ segments: CartLineSegmentDto[];
36
+ };
37
+ /** The unit prices of a cart line: `single` when every unit costs the same (no segments, or one), else the segments. Cart lines only. */
38
+ export declare function lineUnitPrices(line: CartLineDto): LineUnitPrices;
@@ -0,0 +1,28 @@
1
+ import { localProblem, retryAfterSeconds } from "./checkout/types.js";
2
+ function headers(cartToken, opts) {
3
+ const h = { "X-Cart-Token": cartToken, "Idempotency-Key": opts.idempotencyKey ?? crypto.randomUUID() };
4
+ if (opts.ifMatch !== undefined)
5
+ h["If-Match"] = String(opts.ifMatch);
6
+ return h;
7
+ }
8
+ /** `POST /v1/cart/codes`: applies a discount code. A transport failure rejects the promise, like the checkout helpers. */
9
+ export async function applyCode(client, cartToken, code, opts = {}) {
10
+ const { data, error, response } = await (opts.shopper ?? client).POST("/v1/cart/codes", { body: { code }, headers: headers(cartToken, opts) });
11
+ if (error || !data)
12
+ return { ok: false, status: response.status, problem: (error ?? localProblem("SDK_EMPTY_ANSWER", "no body")), retryAfter: retryAfterSeconds(response) };
13
+ return { ok: true, data };
14
+ }
15
+ /** `DELETE /v1/cart/codes/{code}`: removes a discount code (the path segment is URL-encoded). */
16
+ export async function removeCode(client, cartToken, code, opts = {}) {
17
+ const { data, error, response } = await (opts.shopper ?? client).DELETE("/v1/cart/codes/{code}", { params: { path: { code } }, headers: headers(cartToken, opts) });
18
+ if (error || !data)
19
+ return { ok: false, status: response.status, problem: (error ?? localProblem("SDK_EMPTY_ANSWER", "no body")), retryAfter: retryAfterSeconds(response) };
20
+ return { ok: true, data };
21
+ }
22
+ /** The unit prices of a cart line: `single` when every unit costs the same (no segments, or one), else the segments. Cart lines only. */
23
+ export function lineUnitPrices(line) {
24
+ const segments = line.segments;
25
+ if (!segments || segments.length <= 1)
26
+ return { kind: "single", unitPrice: line.unitPrice };
27
+ return { kind: "segments", segments };
28
+ }
package/dist/index.d.ts CHANGED
@@ -68,3 +68,4 @@ export { AnalyticsError, type Ga4Ecommerce, type Ga4Item, type Ga4ItemOptions, t
68
68
  export { SeoError, type BreadcrumbLink, type CollectionHeadOptions, type HeadOptions, type JsonLd, type NextMetadataLike, type ProductJsonLdOptions, type SchemaProperty, type SeoContext, type SeoHead, type SeoMeta, type VariantAvailability, } from "./seo/types.js";
69
69
  export { readVariantParam, redirectTarget, VARIANT_PARAM, variantQueryForApi, variantUrl, type QueryInput, type VariantParam, } from "./variant.js";
70
70
  export { sortOptions, type SortOption } from "./sort.js";
71
+ export { applyCode, removeCode, lineUnitPrices, type CartCodeOptions, type CartCodeResult, type LineUnitPrices } from "./cart-codes.js";
package/dist/index.js CHANGED
@@ -58,3 +58,4 @@ export { AnalyticsError, } from "./analytics/types.js";
58
58
  export { SeoError, } from "./seo/types.js";
59
59
  export { readVariantParam, redirectTarget, VARIANT_PARAM, variantQueryForApi, variantUrl, } from "./variant.js";
60
60
  export { sortOptions } from "./sort.js";
61
+ export { applyCode, removeCode, lineUnitPrices } from "./cart-codes.js";