@wix/himalaya-cli 0.1781.0 → 0.1782.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.
@@ -12,6 +12,32 @@ import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
12
12
  import { hostedCheckoutOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
13
13
  import { formatCurrency } from "../_shared/engine-intl.js";
14
14
  import { logBi, wixErrorCode } from "../_shared/wix-bi.js";
15
+ import { hostSessionFromGlobal } from "@himalaya/iap";
16
+
17
+ /** The host's session clock (a signed-out stub on a host without one). */
18
+ const hostSession = hostSessionFromGlobal();
19
+ /** A web host has no session clock (the stub above always reads signed out): it delivers sign-in and sign-out
20
+ * through the reserved `onIdentityChange` action instead. `undefined` until it first does. Each delivery is a new
21
+ * identity, so it also bumps the generation the members-only cart's rows are checked against. */
22
+ let webSignedIn: boolean | undefined;
23
+ let webGeneration = 0;
24
+ const signedInMember = (): boolean => hostSession.current().kind === "member" || webSignedIn === true;
25
+ /** The members-only cart. Known at BOOT when the screen's bundle is the members-only entry
26
+ * (`himi-branded-lite-member-cart`, which sets the flag before this module runs), so even the boot load never
27
+ * reads a signed-out shopper's cart; also set by a load that names `memberOnly`. */
28
+ let memberOnlyCart = (globalThis as { __himiMemberOnlyCart?: boolean }).__himiMemberOnlyCart === true;
29
+ /** The session generation the rows on show were read under. A members-only cart shows rows only for the CURRENT
30
+ * generation: a member switch while a read or write is in flight never lands the previous member's rows. */
31
+ let rowsGeneration = -1;
32
+ const sessionGeneration = (): number => hostSession.current().generation + webGeneration;
33
+ const memberOnlyArg = (arg: unknown): boolean => (arg as { memberOnly?: unknown } | undefined)?.memberOnly === "1";
34
+ /** Where the in-app cashier returns after payment: this app's own scheme. Another content package on this shell
35
+ * (a Brandy site shell registers its contract's scheme) passes its own on load; only `<scheme>://screen/himi_cart`. */
36
+ let cashierReturnUrl = "himalaya-himi-branded-lite://screen/himi_cart";
37
+ function takeReturnUrl(arg: unknown): void {
38
+ const url = (arg as { returnUrl?: unknown } | undefined)?.returnUrl;
39
+ if (typeof url === "string" && /^[a-z][a-z0-9+.-]*:\/\/screen\/himi_cart$/.test(url)) cashierReturnUrl = url;
40
+ }
15
41
 
16
42
  /** Wix Stores appDefId — the vertical that owns a cart/ecom order, and therefore the
17
43
  * `appId` its cashier order is paid under. (Same constant Wix's own tooling uses.) */
@@ -50,6 +76,9 @@ function cachedUnitPrice(total: string, quantity: number): string {
50
76
  return total.replace(raw, `${grouped}${digits ? decimal + fraction : ""}`);
51
77
  }
52
78
  async function readCachedItems(): Promise<Row[]> {
79
+ // A members-only cart keeps no on-device copy: the cart entity is app-scoped, so one member's rows would show to
80
+ // the next member offline.
81
+ if (memberOnlyCart) return [];
53
82
  try {
54
83
  return ((await getAll(ENTITY)) as unknown as Row[]).map(item => {
55
84
  const quantity = Math.max(1, Math.floor(Number(item.quantity) || 1));
@@ -68,6 +97,7 @@ async function readCachedItems(): Promise<Row[]> {
68
97
  * (one removed elsewhere, or a removal whose answer was lost), so the offline paint never
69
98
  * shows a line that is gone. */
70
99
  async function writeCachedItems(rows: Row[]): Promise<void> {
100
+ if (memberOnlyCart) return;
71
101
  try {
72
102
  const keep = new Set(rows.map((r) => r.id));
73
103
  for (const old of (await getAll(ENTITY)) as unknown as Row[]) if (!keep.has(old.id)) await dbRemove(ENTITY, old.id);
@@ -143,6 +173,12 @@ interface State {
143
173
  hideContent: boolean;
144
174
  noEmpty: boolean;
145
175
  noItems: boolean;
176
+ /** A site shell serves this cart to MEMBERS only (`memberOnly` on load):
177
+ * a native visitor cart is not the website's visitor cart, so a signed-out shopper sees the sign-in gate
178
+ * (`needsSignIn`) instead of a second, separate cart. Absent in Branded Lite, where the visitor cart is native. */
179
+ memberOnly?: boolean;
180
+ needsSignIn?: boolean;
181
+ noSignIn?: boolean;
146
182
  }
147
183
 
148
184
  function itemId(arg: unknown): string {
@@ -256,6 +292,16 @@ function updateLineItemQuantity(cartId: string, lineItemId: string, quantity: nu
256
292
  }
257
293
 
258
294
  function derive(state: State): State {
295
+ // Every state a members-only cart commits passes here, a write's result included: a sign-out while a write was
296
+ // in flight (its identity reload dropped as a concurrent action) still lands on the gate, never the member's rows.
297
+ if (memberOnlyCart && !signedInMember()) {
298
+ state = { ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" };
299
+ } else if (memberOnlyCart && rowsGeneration !== sessionGeneration() && state.items.length > 0) {
300
+ // Rows read under another member (a write's result that landed after the switch): hold a loading state, and
301
+ // reload for this member once the write has settled.
302
+ state = { ...state, memberOnly: true, needsSignIn: false, status: "loading", items: [], subtotal: "", commerceSubtotal: "", checkoutHint: "" };
303
+ queueSessionReload();
304
+ }
259
305
  let savedIds: Set<string> | null = null;
260
306
  try { savedIds = new Set(readSavedProducts().map(row => row.id)); }
261
307
  catch { /* saved storage unavailable: retain the saved flags already shown on each row */ }
@@ -291,6 +337,9 @@ function derive(state: State): State {
291
337
  noPaidToast: !state.showPaidToast,
292
338
  noCoupon: !state.appliedCode,
293
339
  subtotalLabel: copyTemplate("cart.subtotalCount", "Subtotal ({count})", { count: itemCount }),
340
+ noSignIn: !state.needsSignIn,
341
+ // Gated: no content, no empty card, no error card, no checkout footer — only the sign-in gate.
342
+ ...(state.needsSignIn ? { hideContent: true, noEmpty: true, noItems: true, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, noCheckoutHint: true } : {}),
294
343
  };
295
344
  }
296
345
 
@@ -387,7 +436,7 @@ import { withExclusiveWrites } from "../_shared/exclusive-writes.js";
387
436
  let cartPricing: IapCommerce;
388
437
  const defineService = withIapPresentation<State>({
389
438
  register: withExclusiveWrites<State>(withOnlineWrites(registerState, ["remove", "increment", "decrement", "checkout", "beginPromo", "applyPromo", "removePromo"], { derive, messageFields: action => action.includes("Promo") ? ["promoError"] : ["checkoutHint"] }), ["load", "remove", "increment", "decrement", "checkout", "applyPromo", "removePromo", "save"], {
390
- prepare: (action, args) => { if (action === "load") stashCopy(args[0]); },
439
+ prepare: (action, args) => { if (action === "load") { stashCopy(args[0]); if (memberOnlyArg(args[0])) memberOnlyCart = true; takeReturnUrl(args[0]); } },
391
440
  coalesce: ["load"],
392
441
  // Full cart reloads share the transaction, since they also replace rows and
393
442
  // reset promo fields. Only setPromo increments the edit revision: beginPromo's internal error reset
@@ -418,10 +467,36 @@ const svc = defineService<State, {
418
467
  increment: (state: State, arg?: unknown) => Promise<State>;
419
468
  decrement: (state: State, arg?: unknown) => Promise<State>;
420
469
  checkout: (state: State) => Promise<State>;
470
+ dropForSession: (state: State) => State;
471
+ onIdentityChange: (state: State, change?: unknown) => State;
421
472
  }>("himiStoreCart", {
422
- state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true }),
473
+ state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true, memberOnly: false, needsSignIn: false, noSignIn: true }),
423
474
  actions: {
475
+ // Not a write: it runs even while one is in flight, so a member switch clears the previous member's rows AT ONCE.
476
+ dropForSession: (state) => derive(state),
477
+ // The web host's identity hook (see `webSignedIn`): a members-only cart follows it as it follows the native clock.
478
+ onIdentityChange: (state, change) => {
479
+ webSignedIn = (change as { signedIn?: unknown } | undefined)?.signedIn === true;
480
+ webGeneration++;
481
+ if (memberOnlyCart) queueSessionReload();
482
+ return derive(state);
483
+ },
424
484
  load: async (state, arg) => {
485
+ // A members-only cart (a site shell) never shows a signed-out shopper's native cart. `prepare` sets the flag
486
+ // before coalescing, so a load already in flight (the boot load) re-checks it before it lands.
487
+ if (memberOnlyArg(arg)) memberOnlyCart = true;
488
+ const gated = (): State => derive({ ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" });
489
+ if (memberOnlyCart && !signedInMember()) return gated();
490
+ if (memberOnlyCart) state = { ...state, memberOnly: true, needsSignIn: false };
491
+ const readUnder = sessionGeneration();
492
+ // This read is for the current member: rows it derives stand until the generation moves on.
493
+ if (memberOnlyCart) rowsGeneration = readUnder;
494
+ const landed = (next: State): State => {
495
+ if (!memberOnlyCart) return next;
496
+ if (!signedInMember()) return gated();
497
+ if (sessionGeneration() !== readUnder) { reloadForSession(); return derive({ ...next, memberOnly: true, needsSignIn: false, status: "loading", items: [] }); }
498
+ return derive({ ...next, memberOnly: true, needsSignIn: false });
499
+ };
425
500
  // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
426
501
  const cached = await readCachedItems();
427
502
  const base = cached.length
@@ -429,12 +504,12 @@ const svc = defineService<State, {
429
504
  : state;
430
505
  // 2) Revalidate from Wix and refresh the cache.
431
506
  try {
432
- return await refresh(state);
507
+ return landed(await refresh(state));
433
508
  } catch (error) {
434
509
  // Offline / fetch failure: keep the cached items instead of a blank error state.
435
- return cached.length
510
+ return landed(cached.length
436
511
  ? base
437
- : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" });
512
+ : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" }));
438
513
  }
439
514
  },
440
515
  setPromo: (state, arg) => derive({ ...state, promoEditRevision: (state.promoEditRevision ?? 0) + 1, promoCode: (typeof arg === "string" ? arg : String((arg as { value?: unknown } | undefined)?.value ?? "")).slice(0, 100), promoError: "" }),
@@ -587,7 +662,7 @@ const svc = defineService<State, {
587
662
  cashierUrl: async () => {
588
663
  const redirect = await createRedirectSession({
589
664
  ecomCheckout: { checkoutId },
590
- callbacks: { postFlowUrl: "himalaya-himi-branded-lite://screen/himi_cart" },
665
+ callbacks: { postFlowUrl: cashierReturnUrl },
591
666
  });
592
667
  return redirect.redirectSession?.fullUrl;
593
668
  },
@@ -607,5 +682,22 @@ const svc = defineService<State, {
607
682
  },
608
683
  });
609
684
 
685
+ /** Reload until the rows on show are this session generation's. A load that coalesces into one already in flight
686
+ * (or is dropped behind a write) returns before reading, so try again once it settles (a coalesced call resolves when the load in flight completes); a few tries bound it. */
687
+ /** From `derive`: reload after the commit in progress has settled (a few promise turns later). Once per stale streak. */
688
+ let sessionReloadQueued = false;
689
+ function queueSessionReload(): void {
690
+ if (sessionReloadQueued) return;
691
+ sessionReloadQueued = true;
692
+ void Promise.resolve().then(() => undefined).then(() => undefined).then(() => { sessionReloadQueued = false; reloadForSession(); });
693
+ }
694
+ function reloadForSession(tries = 4): void {
695
+ void Promise.resolve(svc.load()).finally(() => {
696
+ if (tries > 1 && memberOnlyCart && signedInMember() && rowsGeneration !== sessionGeneration()) reloadForSession(tries - 1);
697
+ });
698
+ }
610
699
  svc.load();
700
+ // A members-only cart follows the signed-in identity: a sign-in shows the member's cart, a sign-out the gate.
701
+ // The host clock notifies at once on subscribe, which the boot load above already covers.
702
+ hostSession.subscribe(() => { if (memberOnlyCart) { void svc.dropForSession(); reloadForSession(); } });
611
703
  export { svc };
@@ -12,6 +12,32 @@ import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
12
12
  import { hostedCheckoutOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
13
13
  import { formatCurrency } from "../_shared/engine-intl.js";
14
14
  import { logBi, wixErrorCode } from "../_shared/wix-bi.js";
15
+ import { hostSessionFromGlobal } from "@himalaya/iap";
16
+
17
+ /** The host's session clock (a signed-out stub on a host without one). */
18
+ const hostSession = hostSessionFromGlobal();
19
+ /** A web host has no session clock (the stub above always reads signed out): it delivers sign-in and sign-out
20
+ * through the reserved `onIdentityChange` action instead. `undefined` until it first does. Each delivery is a new
21
+ * identity, so it also bumps the generation the members-only cart's rows are checked against. */
22
+ let webSignedIn: boolean | undefined;
23
+ let webGeneration = 0;
24
+ const signedInMember = (): boolean => hostSession.current().kind === "member" || webSignedIn === true;
25
+ /** The members-only cart. Known at BOOT when the screen's bundle is the members-only entry
26
+ * (`himi-branded-lite-member-cart`, which sets the flag before this module runs), so even the boot load never
27
+ * reads a signed-out shopper's cart; also set by a load that names `memberOnly`. */
28
+ let memberOnlyCart = (globalThis as { __himiMemberOnlyCart?: boolean }).__himiMemberOnlyCart === true;
29
+ /** The session generation the rows on show were read under. A members-only cart shows rows only for the CURRENT
30
+ * generation: a member switch while a read or write is in flight never lands the previous member's rows. */
31
+ let rowsGeneration = -1;
32
+ const sessionGeneration = (): number => hostSession.current().generation + webGeneration;
33
+ const memberOnlyArg = (arg: unknown): boolean => (arg as { memberOnly?: unknown } | undefined)?.memberOnly === "1";
34
+ /** Where the in-app cashier returns after payment: this app's own scheme. Another content package on this shell
35
+ * (a Brandy site shell registers its contract's scheme) passes its own on load; only `<scheme>://screen/himi_cart`. */
36
+ let cashierReturnUrl = "himalaya-himi-branded-lite://screen/himi_cart";
37
+ function takeReturnUrl(arg: unknown): void {
38
+ const url = (arg as { returnUrl?: unknown } | undefined)?.returnUrl;
39
+ if (typeof url === "string" && /^[a-z][a-z0-9+.-]*:\/\/screen\/himi_cart$/.test(url)) cashierReturnUrl = url;
40
+ }
15
41
 
16
42
  /** Wix Stores appDefId — the vertical that owns a cart/ecom order, and therefore the
17
43
  * `appId` its cashier order is paid under. (Same constant Wix's own tooling uses.) */
@@ -50,6 +76,9 @@ function cachedUnitPrice(total: string, quantity: number): string {
50
76
  return total.replace(raw, `${grouped}${digits ? decimal + fraction : ""}`);
51
77
  }
52
78
  async function readCachedItems(): Promise<Row[]> {
79
+ // A members-only cart keeps no on-device copy: the cart entity is app-scoped, so one member's rows would show to
80
+ // the next member offline.
81
+ if (memberOnlyCart) return [];
53
82
  try {
54
83
  return ((await getAll(ENTITY)) as unknown as Row[]).map(item => {
55
84
  const quantity = Math.max(1, Math.floor(Number(item.quantity) || 1));
@@ -68,6 +97,7 @@ async function readCachedItems(): Promise<Row[]> {
68
97
  * (one removed elsewhere, or a removal whose answer was lost), so the offline paint never
69
98
  * shows a line that is gone. */
70
99
  async function writeCachedItems(rows: Row[]): Promise<void> {
100
+ if (memberOnlyCart) return;
71
101
  try {
72
102
  const keep = new Set(rows.map((r) => r.id));
73
103
  for (const old of (await getAll(ENTITY)) as unknown as Row[]) if (!keep.has(old.id)) await dbRemove(ENTITY, old.id);
@@ -143,6 +173,12 @@ interface State {
143
173
  hideContent: boolean;
144
174
  noEmpty: boolean;
145
175
  noItems: boolean;
176
+ /** A site shell serves this cart to MEMBERS only (`memberOnly` on load):
177
+ * a native visitor cart is not the website's visitor cart, so a signed-out shopper sees the sign-in gate
178
+ * (`needsSignIn`) instead of a second, separate cart. Absent in Branded Lite, where the visitor cart is native. */
179
+ memberOnly?: boolean;
180
+ needsSignIn?: boolean;
181
+ noSignIn?: boolean;
146
182
  }
147
183
 
148
184
  function itemId(arg: unknown): string {
@@ -256,6 +292,16 @@ function updateLineItemQuantity(cartId: string, lineItemId: string, quantity: nu
256
292
  }
257
293
 
258
294
  function derive(state: State): State {
295
+ // Every state a members-only cart commits passes here, a write's result included: a sign-out while a write was
296
+ // in flight (its identity reload dropped as a concurrent action) still lands on the gate, never the member's rows.
297
+ if (memberOnlyCart && !signedInMember()) {
298
+ state = { ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" };
299
+ } else if (memberOnlyCart && rowsGeneration !== sessionGeneration() && state.items.length > 0) {
300
+ // Rows read under another member (a write's result that landed after the switch): hold a loading state, and
301
+ // reload for this member once the write has settled.
302
+ state = { ...state, memberOnly: true, needsSignIn: false, status: "loading", items: [], subtotal: "", commerceSubtotal: "", checkoutHint: "" };
303
+ queueSessionReload();
304
+ }
259
305
  let savedIds: Set<string> | null = null;
260
306
  try { savedIds = new Set(readSavedProducts().map(row => row.id)); }
261
307
  catch { /* saved storage unavailable: retain the saved flags already shown on each row */ }
@@ -291,6 +337,9 @@ function derive(state: State): State {
291
337
  noPaidToast: !state.showPaidToast,
292
338
  noCoupon: !state.appliedCode,
293
339
  subtotalLabel: copyTemplate("cart.subtotalCount", "Subtotal ({count})", { count: itemCount }),
340
+ noSignIn: !state.needsSignIn,
341
+ // Gated: no content, no empty card, no error card, no checkout footer — only the sign-in gate.
342
+ ...(state.needsSignIn ? { hideContent: true, noEmpty: true, noItems: true, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, noCheckoutHint: true } : {}),
294
343
  };
295
344
  }
296
345
 
@@ -387,7 +436,7 @@ import { withExclusiveWrites } from "../_shared/exclusive-writes.js";
387
436
  let cartPricing: IapCommerce;
388
437
  const defineService = withIapPresentation<State>({
389
438
  register: withExclusiveWrites<State>(withOnlineWrites(registerState, ["remove", "increment", "decrement", "checkout", "beginPromo", "applyPromo", "removePromo"], { derive, messageFields: action => action.includes("Promo") ? ["promoError"] : ["checkoutHint"] }), ["load", "remove", "increment", "decrement", "checkout", "applyPromo", "removePromo", "save"], {
390
- prepare: (action, args) => { if (action === "load") stashCopy(args[0]); },
439
+ prepare: (action, args) => { if (action === "load") { stashCopy(args[0]); if (memberOnlyArg(args[0])) memberOnlyCart = true; takeReturnUrl(args[0]); } },
391
440
  coalesce: ["load"],
392
441
  // Full cart reloads share the transaction, since they also replace rows and
393
442
  // reset promo fields. Only setPromo increments the edit revision: beginPromo's internal error reset
@@ -418,10 +467,36 @@ const svc = defineService<State, {
418
467
  increment: (state: State, arg?: unknown) => Promise<State>;
419
468
  decrement: (state: State, arg?: unknown) => Promise<State>;
420
469
  checkout: (state: State) => Promise<State>;
470
+ dropForSession: (state: State) => State;
471
+ onIdentityChange: (state: State, change?: unknown) => State;
421
472
  }>("himiStoreCart", {
422
- state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true }),
473
+ state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true, memberOnly: false, needsSignIn: false, noSignIn: true }),
423
474
  actions: {
475
+ // Not a write: it runs even while one is in flight, so a member switch clears the previous member's rows AT ONCE.
476
+ dropForSession: (state) => derive(state),
477
+ // The web host's identity hook (see `webSignedIn`): a members-only cart follows it as it follows the native clock.
478
+ onIdentityChange: (state, change) => {
479
+ webSignedIn = (change as { signedIn?: unknown } | undefined)?.signedIn === true;
480
+ webGeneration++;
481
+ if (memberOnlyCart) queueSessionReload();
482
+ return derive(state);
483
+ },
424
484
  load: async (state, arg) => {
485
+ // A members-only cart (a site shell) never shows a signed-out shopper's native cart. `prepare` sets the flag
486
+ // before coalescing, so a load already in flight (the boot load) re-checks it before it lands.
487
+ if (memberOnlyArg(arg)) memberOnlyCart = true;
488
+ const gated = (): State => derive({ ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" });
489
+ if (memberOnlyCart && !signedInMember()) return gated();
490
+ if (memberOnlyCart) state = { ...state, memberOnly: true, needsSignIn: false };
491
+ const readUnder = sessionGeneration();
492
+ // This read is for the current member: rows it derives stand until the generation moves on.
493
+ if (memberOnlyCart) rowsGeneration = readUnder;
494
+ const landed = (next: State): State => {
495
+ if (!memberOnlyCart) return next;
496
+ if (!signedInMember()) return gated();
497
+ if (sessionGeneration() !== readUnder) { reloadForSession(); return derive({ ...next, memberOnly: true, needsSignIn: false, status: "loading", items: [] }); }
498
+ return derive({ ...next, memberOnly: true, needsSignIn: false });
499
+ };
425
500
  // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
426
501
  const cached = await readCachedItems();
427
502
  const base = cached.length
@@ -429,12 +504,12 @@ const svc = defineService<State, {
429
504
  : state;
430
505
  // 2) Revalidate from Wix and refresh the cache.
431
506
  try {
432
- return await refresh(state);
507
+ return landed(await refresh(state));
433
508
  } catch (error) {
434
509
  // Offline / fetch failure: keep the cached items instead of a blank error state.
435
- return cached.length
510
+ return landed(cached.length
436
511
  ? base
437
- : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" });
512
+ : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" }));
438
513
  }
439
514
  },
440
515
  setPromo: (state, arg) => derive({ ...state, promoEditRevision: (state.promoEditRevision ?? 0) + 1, promoCode: (typeof arg === "string" ? arg : String((arg as { value?: unknown } | undefined)?.value ?? "")).slice(0, 100), promoError: "" }),
@@ -587,7 +662,7 @@ const svc = defineService<State, {
587
662
  cashierUrl: async () => {
588
663
  const redirect = await createRedirectSession({
589
664
  ecomCheckout: { checkoutId },
590
- callbacks: { postFlowUrl: "himalaya-himi-branded-lite://screen/himi_cart" },
665
+ callbacks: { postFlowUrl: cashierReturnUrl },
591
666
  });
592
667
  return redirect.redirectSession?.fullUrl;
593
668
  },
@@ -607,5 +682,22 @@ const svc = defineService<State, {
607
682
  },
608
683
  });
609
684
 
685
+ /** Reload until the rows on show are this session generation's. A load that coalesces into one already in flight
686
+ * (or is dropped behind a write) returns before reading, so try again once it settles (a coalesced call resolves when the load in flight completes); a few tries bound it. */
687
+ /** From `derive`: reload after the commit in progress has settled (a few promise turns later). Once per stale streak. */
688
+ let sessionReloadQueued = false;
689
+ function queueSessionReload(): void {
690
+ if (sessionReloadQueued) return;
691
+ sessionReloadQueued = true;
692
+ void Promise.resolve().then(() => undefined).then(() => undefined).then(() => { sessionReloadQueued = false; reloadForSession(); });
693
+ }
694
+ function reloadForSession(tries = 4): void {
695
+ void Promise.resolve(svc.load()).finally(() => {
696
+ if (tries > 1 && memberOnlyCart && signedInMember() && rowsGeneration !== sessionGeneration()) reloadForSession(tries - 1);
697
+ });
698
+ }
610
699
  svc.load();
700
+ // A members-only cart follows the signed-in identity: a sign-in shows the member's cart, a sign-out the gate.
701
+ // The host clock notifies at once on subscribe, which the boot load above already covers.
702
+ hostSession.subscribe(() => { if (memberOnlyCart) { void svc.dropForSession(); reloadForSession(); } });
611
703
  export { svc };
@@ -12,6 +12,32 @@ import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
12
12
  import { hostedCheckoutOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
13
13
  import { formatCurrency } from "../_shared/engine-intl.js";
14
14
  import { logBi, wixErrorCode } from "../_shared/wix-bi.js";
15
+ import { hostSessionFromGlobal } from "@himalaya/iap";
16
+
17
+ /** The host's session clock (a signed-out stub on a host without one). */
18
+ const hostSession = hostSessionFromGlobal();
19
+ /** A web host has no session clock (the stub above always reads signed out): it delivers sign-in and sign-out
20
+ * through the reserved `onIdentityChange` action instead. `undefined` until it first does. Each delivery is a new
21
+ * identity, so it also bumps the generation the members-only cart's rows are checked against. */
22
+ let webSignedIn: boolean | undefined;
23
+ let webGeneration = 0;
24
+ const signedInMember = (): boolean => hostSession.current().kind === "member" || webSignedIn === true;
25
+ /** The members-only cart. Known at BOOT when the screen's bundle is the members-only entry
26
+ * (`himi-branded-lite-member-cart`, which sets the flag before this module runs), so even the boot load never
27
+ * reads a signed-out shopper's cart; also set by a load that names `memberOnly`. */
28
+ let memberOnlyCart = (globalThis as { __himiMemberOnlyCart?: boolean }).__himiMemberOnlyCart === true;
29
+ /** The session generation the rows on show were read under. A members-only cart shows rows only for the CURRENT
30
+ * generation: a member switch while a read or write is in flight never lands the previous member's rows. */
31
+ let rowsGeneration = -1;
32
+ const sessionGeneration = (): number => hostSession.current().generation + webGeneration;
33
+ const memberOnlyArg = (arg: unknown): boolean => (arg as { memberOnly?: unknown } | undefined)?.memberOnly === "1";
34
+ /** Where the in-app cashier returns after payment: this app's own scheme. Another content package on this shell
35
+ * (a Brandy site shell registers its contract's scheme) passes its own on load; only `<scheme>://screen/himi_cart`. */
36
+ let cashierReturnUrl = "himalaya-himi-branded-lite://screen/himi_cart";
37
+ function takeReturnUrl(arg: unknown): void {
38
+ const url = (arg as { returnUrl?: unknown } | undefined)?.returnUrl;
39
+ if (typeof url === "string" && /^[a-z][a-z0-9+.-]*:\/\/screen\/himi_cart$/.test(url)) cashierReturnUrl = url;
40
+ }
15
41
 
16
42
  /** Wix Stores appDefId — the vertical that owns a cart/ecom order, and therefore the
17
43
  * `appId` its cashier order is paid under. (Same constant Wix's own tooling uses.) */
@@ -50,6 +76,9 @@ function cachedUnitPrice(total: string, quantity: number): string {
50
76
  return total.replace(raw, `${grouped}${digits ? decimal + fraction : ""}`);
51
77
  }
52
78
  async function readCachedItems(): Promise<Row[]> {
79
+ // A members-only cart keeps no on-device copy: the cart entity is app-scoped, so one member's rows would show to
80
+ // the next member offline.
81
+ if (memberOnlyCart) return [];
53
82
  try {
54
83
  return ((await getAll(ENTITY)) as unknown as Row[]).map(item => {
55
84
  const quantity = Math.max(1, Math.floor(Number(item.quantity) || 1));
@@ -68,6 +97,7 @@ async function readCachedItems(): Promise<Row[]> {
68
97
  * (one removed elsewhere, or a removal whose answer was lost), so the offline paint never
69
98
  * shows a line that is gone. */
70
99
  async function writeCachedItems(rows: Row[]): Promise<void> {
100
+ if (memberOnlyCart) return;
71
101
  try {
72
102
  const keep = new Set(rows.map((r) => r.id));
73
103
  for (const old of (await getAll(ENTITY)) as unknown as Row[]) if (!keep.has(old.id)) await dbRemove(ENTITY, old.id);
@@ -143,6 +173,12 @@ interface State {
143
173
  hideContent: boolean;
144
174
  noEmpty: boolean;
145
175
  noItems: boolean;
176
+ /** A site shell serves this cart to MEMBERS only (`memberOnly` on load):
177
+ * a native visitor cart is not the website's visitor cart, so a signed-out shopper sees the sign-in gate
178
+ * (`needsSignIn`) instead of a second, separate cart. Absent in Branded Lite, where the visitor cart is native. */
179
+ memberOnly?: boolean;
180
+ needsSignIn?: boolean;
181
+ noSignIn?: boolean;
146
182
  }
147
183
 
148
184
  function itemId(arg: unknown): string {
@@ -256,6 +292,16 @@ function updateLineItemQuantity(cartId: string, lineItemId: string, quantity: nu
256
292
  }
257
293
 
258
294
  function derive(state: State): State {
295
+ // Every state a members-only cart commits passes here, a write's result included: a sign-out while a write was
296
+ // in flight (its identity reload dropped as a concurrent action) still lands on the gate, never the member's rows.
297
+ if (memberOnlyCart && !signedInMember()) {
298
+ state = { ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" };
299
+ } else if (memberOnlyCart && rowsGeneration !== sessionGeneration() && state.items.length > 0) {
300
+ // Rows read under another member (a write's result that landed after the switch): hold a loading state, and
301
+ // reload for this member once the write has settled.
302
+ state = { ...state, memberOnly: true, needsSignIn: false, status: "loading", items: [], subtotal: "", commerceSubtotal: "", checkoutHint: "" };
303
+ queueSessionReload();
304
+ }
259
305
  let savedIds: Set<string> | null = null;
260
306
  try { savedIds = new Set(readSavedProducts().map(row => row.id)); }
261
307
  catch { /* saved storage unavailable: retain the saved flags already shown on each row */ }
@@ -291,6 +337,9 @@ function derive(state: State): State {
291
337
  noPaidToast: !state.showPaidToast,
292
338
  noCoupon: !state.appliedCode,
293
339
  subtotalLabel: copyTemplate("cart.subtotalCount", "Subtotal ({count})", { count: itemCount }),
340
+ noSignIn: !state.needsSignIn,
341
+ // Gated: no content, no empty card, no error card, no checkout footer — only the sign-in gate.
342
+ ...(state.needsSignIn ? { hideContent: true, noEmpty: true, noItems: true, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, noCheckoutHint: true } : {}),
294
343
  };
295
344
  }
296
345
 
@@ -387,7 +436,7 @@ import { withExclusiveWrites } from "../_shared/exclusive-writes.js";
387
436
  let cartPricing: IapCommerce;
388
437
  const defineService = withIapPresentation<State>({
389
438
  register: withExclusiveWrites<State>(withOnlineWrites(registerState, ["remove", "increment", "decrement", "checkout", "beginPromo", "applyPromo", "removePromo"], { derive, messageFields: action => action.includes("Promo") ? ["promoError"] : ["checkoutHint"] }), ["load", "remove", "increment", "decrement", "checkout", "applyPromo", "removePromo", "save"], {
390
- prepare: (action, args) => { if (action === "load") stashCopy(args[0]); },
439
+ prepare: (action, args) => { if (action === "load") { stashCopy(args[0]); if (memberOnlyArg(args[0])) memberOnlyCart = true; takeReturnUrl(args[0]); } },
391
440
  coalesce: ["load"],
392
441
  // Full cart reloads share the transaction, since they also replace rows and
393
442
  // reset promo fields. Only setPromo increments the edit revision: beginPromo's internal error reset
@@ -418,10 +467,36 @@ const svc = defineService<State, {
418
467
  increment: (state: State, arg?: unknown) => Promise<State>;
419
468
  decrement: (state: State, arg?: unknown) => Promise<State>;
420
469
  checkout: (state: State) => Promise<State>;
470
+ dropForSession: (state: State) => State;
471
+ onIdentityChange: (state: State, change?: unknown) => State;
421
472
  }>("himiStoreCart", {
422
- state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true }),
473
+ state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true, memberOnly: false, needsSignIn: false, noSignIn: true }),
423
474
  actions: {
475
+ // Not a write: it runs even while one is in flight, so a member switch clears the previous member's rows AT ONCE.
476
+ dropForSession: (state) => derive(state),
477
+ // The web host's identity hook (see `webSignedIn`): a members-only cart follows it as it follows the native clock.
478
+ onIdentityChange: (state, change) => {
479
+ webSignedIn = (change as { signedIn?: unknown } | undefined)?.signedIn === true;
480
+ webGeneration++;
481
+ if (memberOnlyCart) queueSessionReload();
482
+ return derive(state);
483
+ },
424
484
  load: async (state, arg) => {
485
+ // A members-only cart (a site shell) never shows a signed-out shopper's native cart. `prepare` sets the flag
486
+ // before coalescing, so a load already in flight (the boot load) re-checks it before it lands.
487
+ if (memberOnlyArg(arg)) memberOnlyCart = true;
488
+ const gated = (): State => derive({ ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" });
489
+ if (memberOnlyCart && !signedInMember()) return gated();
490
+ if (memberOnlyCart) state = { ...state, memberOnly: true, needsSignIn: false };
491
+ const readUnder = sessionGeneration();
492
+ // This read is for the current member: rows it derives stand until the generation moves on.
493
+ if (memberOnlyCart) rowsGeneration = readUnder;
494
+ const landed = (next: State): State => {
495
+ if (!memberOnlyCart) return next;
496
+ if (!signedInMember()) return gated();
497
+ if (sessionGeneration() !== readUnder) { reloadForSession(); return derive({ ...next, memberOnly: true, needsSignIn: false, status: "loading", items: [] }); }
498
+ return derive({ ...next, memberOnly: true, needsSignIn: false });
499
+ };
425
500
  // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
426
501
  const cached = await readCachedItems();
427
502
  const base = cached.length
@@ -429,12 +504,12 @@ const svc = defineService<State, {
429
504
  : state;
430
505
  // 2) Revalidate from Wix and refresh the cache.
431
506
  try {
432
- return await refresh(state);
507
+ return landed(await refresh(state));
433
508
  } catch (error) {
434
509
  // Offline / fetch failure: keep the cached items instead of a blank error state.
435
- return cached.length
510
+ return landed(cached.length
436
511
  ? base
437
- : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" });
512
+ : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" }));
438
513
  }
439
514
  },
440
515
  setPromo: (state, arg) => derive({ ...state, promoEditRevision: (state.promoEditRevision ?? 0) + 1, promoCode: (typeof arg === "string" ? arg : String((arg as { value?: unknown } | undefined)?.value ?? "")).slice(0, 100), promoError: "" }),
@@ -587,7 +662,7 @@ const svc = defineService<State, {
587
662
  cashierUrl: async () => {
588
663
  const redirect = await createRedirectSession({
589
664
  ecomCheckout: { checkoutId },
590
- callbacks: { postFlowUrl: "himalaya-himi-branded-lite://screen/himi_cart" },
665
+ callbacks: { postFlowUrl: cashierReturnUrl },
591
666
  });
592
667
  return redirect.redirectSession?.fullUrl;
593
668
  },
@@ -607,5 +682,22 @@ const svc = defineService<State, {
607
682
  },
608
683
  });
609
684
 
685
+ /** Reload until the rows on show are this session generation's. A load that coalesces into one already in flight
686
+ * (or is dropped behind a write) returns before reading, so try again once it settles (a coalesced call resolves when the load in flight completes); a few tries bound it. */
687
+ /** From `derive`: reload after the commit in progress has settled (a few promise turns later). Once per stale streak. */
688
+ let sessionReloadQueued = false;
689
+ function queueSessionReload(): void {
690
+ if (sessionReloadQueued) return;
691
+ sessionReloadQueued = true;
692
+ void Promise.resolve().then(() => undefined).then(() => undefined).then(() => { sessionReloadQueued = false; reloadForSession(); });
693
+ }
694
+ function reloadForSession(tries = 4): void {
695
+ void Promise.resolve(svc.load()).finally(() => {
696
+ if (tries > 1 && memberOnlyCart && signedInMember() && rowsGeneration !== sessionGeneration()) reloadForSession(tries - 1);
697
+ });
698
+ }
610
699
  svc.load();
700
+ // A members-only cart follows the signed-in identity: a sign-in shows the member's cart, a sign-out the gate.
701
+ // The host clock notifies at once on subscribe, which the boot load above already covers.
702
+ hostSession.subscribe(() => { if (memberOnlyCart) { void svc.dropForSession(); reloadForSession(); } });
611
703
  export { svc };