@wix/himalaya-cli 0.1806.0 → 0.1808.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.
Files changed (25) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/site-shell.d.ts +62 -1
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +124 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +12 -0
  4. package/dist/cli.mjs +13 -1
  5. package/package.json +2 -2
  6. package/templates/brandy/README.md +83 -14
  7. package/templates/brandy/config.ts +42 -34
  8. package/templates/brandy/dev/index.ts +240 -21
  9. package/templates/brandy/dev/member-screens.ts +2302 -0
  10. package/templates/brandy/himalaya.content.json +3 -0
  11. package/templates/brandy/himalaya.template.json +1 -1
  12. package/templates/brandy/provisioning.json +4 -1
  13. package/templates/brandy/provisioning.member.example.json +69 -7
  14. package/templates/brandy/tier5-src/_shared/exclusive-writes.ts +66 -0
  15. package/templates/brandy/tier5-src/_shared/header-badges.ts +113 -0
  16. package/templates/brandy/tier5-src/_shared/himi-store-saved.ts +57 -0
  17. package/templates/brandy/tier5-src/_shared/iap-presentation.ts +207 -0
  18. package/templates/brandy/tier5-src/_shared/restaurant-ordering.ts +201 -0
  19. package/templates/brandy/tier5-src/_shared/source-badges.ts +72 -0
  20. package/templates/brandy/tier5-src/himi-branded-lite-cart/index.ts +703 -0
  21. package/templates/brandy/tier5-src/himi-branded-lite-header-badges/index.ts +70 -0
  22. package/templates/brandy/tier5-src/himi-branded-lite-member-cart/flag.ts +3 -0
  23. package/templates/brandy/tier5-src/himi-branded-lite-member-cart/index.ts +6 -0
  24. package/templates/brandy/tier5-src/perks/index.ts +75 -0
  25. package/templates/brandy/tokens.json +5 -0
@@ -13,6 +13,9 @@
13
13
  "site_contact": {
14
14
  "displayName": "Contact"
15
15
  },
16
+ "perks": {
17
+ "displayName": "Perks"
18
+ },
16
19
  "himi_notification_settings": {
17
20
  "displayName": "Notifications"
18
21
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "title": "Brandy — your website as an app",
3
- "description": "A site shell: the customer's live website (Wix, Base44, or any https site with site.kind \"web\") as a native app. Every tab and drawer row is one of the site's own pages in a native-framed WebView, with a native tab bar, drawer, splash and brand colours; on a Wix site, its header, footer and Wix ads are hidden. The page map lives in provisioning.json (`site`), and `himi site analyze --url <site>` derives it from the site's own menu. It runs on the Branded Lite shell (`himi dist` builds that shell; an existing Brandy app keeps its identity with `--shell brandy`). Start here to ship an existing website as an app today and move tabs to native screens later.",
3
+ "description": "A site shell: the customer's live website (Wix, Base44, or any https site with site.kind \"web\") as a native app. The site's own pages fill the tabs and drawer in native-framed WebViews, with a native tab bar, drawer, splash and brand colours, beside native screens: a sample Perks tab, and with a Wix member login native Account, Notifications and Cart (with a live cart count); on a Wix site, its header, footer and Wix ads are hidden. The page map lives in provisioning.json (`site`), and `himi site analyze --url <site>` derives it from the site's own menu. It runs on the Branded Lite shell (`himi dist` builds that shell; an existing Brandy app keeps its identity with `--shell brandy`). Start here to ship an existing website as an app today and move tabs to native screens later.",
4
4
  "tags": ["wix", "website", "site-shell", "webview", "tabs", "drawer", "no-code", "day-zero", "consumer"],
5
5
  "category": "consumer"
6
6
  }
@@ -7,6 +7,9 @@
7
7
  { "id": "blog", "title": "Blog", "path": "/blog", "icon": "newspaper" },
8
8
  { "id": "contact", "title": "Contact", "path": "/contact", "icon": "mail", "placement": "drawer" }
9
9
  ],
10
- "chrome": { "hideSiteHeader": true, "hideSiteMenu": true, "hideSiteFooter": true, "hideWixAds": true }
10
+ "chrome": { "hideSiteHeader": true, "hideSiteMenu": true, "hideSiteFooter": true, "hideWixAds": true },
11
+ "nativePages": [
12
+ { "id": "perks", "screenId": "perks", "title": "Perks", "icon": "gift" }
13
+ ]
11
14
  }
12
15
  }
@@ -3,18 +3,80 @@
3
3
  "origin": "https://your-account.wixsite.com/your-site",
4
4
  "kind": "wix",
5
5
  "pages": [
6
- { "id": "home", "title": "Home", "path": "/", "icon": "home" },
7
- { "id": "blog", "title": "Blog", "path": "/blog", "icon": "newspaper" },
8
- { "id": "contact", "title": "Contact", "path": "/contact", "icon": "mail", "placement": "drawer" }
6
+ {
7
+ "id": "home",
8
+ "title": "Home",
9
+ "path": "/",
10
+ "icon": "home"
11
+ },
12
+ {
13
+ "id": "blog",
14
+ "title": "Blog",
15
+ "path": "/blog",
16
+ "icon": "newspaper"
17
+ },
18
+ {
19
+ "id": "contact",
20
+ "title": "Contact",
21
+ "path": "/contact",
22
+ "icon": "mail",
23
+ "placement": "drawer"
24
+ }
9
25
  ],
10
- "chrome": { "hideSiteHeader": true, "hideSiteFooter": true, "hideWixAds": true },
26
+ "chrome": {
27
+ "hideSiteHeader": true,
28
+ "hideSiteFooter": true,
29
+ "hideWixAds": true
30
+ },
11
31
  "nativePages": [
12
- { "id": "my_account", "screenId": "himi_account", "title": "Account", "icon": "person", "placement": "drawer" },
13
- { "id": "activity", "screenId": "himi_notifications", "title": "Notifications", "icon": "bell", "placement": "drawer", "public": true }
32
+ {
33
+ "id": "perks",
34
+ "screenId": "perks",
35
+ "title": "Perks",
36
+ "icon": "gift"
37
+ },
38
+ {
39
+ "id": "my_account",
40
+ "screenId": "himi_account",
41
+ "title": "Account",
42
+ "icon": "person",
43
+ "placement": "drawer"
44
+ },
45
+ {
46
+ "id": "activity",
47
+ "screenId": "himi_notifications",
48
+ "title": "Notifications",
49
+ "icon": "bell",
50
+ "placement": "drawer",
51
+ "public": true
52
+ },
53
+ {
54
+ "id": "cart",
55
+ "screenId": "himi_cart",
56
+ "title": "Cart",
57
+ "icon": "cart",
58
+ "placement": "drawer",
59
+ "requiresAuth": true
60
+ }
14
61
  ],
15
62
  "topBar": {
16
63
  "actions": [
17
- { "id": "notifications", "icon": "bell", "label": "Notifications", "target": { "screen": "himi_notifications" } }
64
+ {
65
+ "id": "cart",
66
+ "icon": "cart",
67
+ "label": "Cart",
68
+ "target": {
69
+ "screen": "himi_cart"
70
+ }
71
+ },
72
+ {
73
+ "id": "account",
74
+ "icon": "person",
75
+ "label": "Account",
76
+ "target": {
77
+ "screen": "himi_account"
78
+ }
79
+ }
18
80
  ]
19
81
  }
20
82
  },
@@ -0,0 +1,66 @@
1
+ import { defineService as register, type ServiceDefinition } from '@himalaya/state';
2
+
3
+ /** Reject repeated taps until the accepted write's result is committed. A promise
4
+ * queue alone releases before the host applies the reducer result, so the next
5
+ * write can still read an old revision/id. The private synchronous reducer below
6
+ * publishes busy and commits completion through the ordinary service handle;
7
+ * awaiting that handle guarantees the host has stored the result before unlock.
8
+ * Skipped actions return undefined, so they cannot roll back the accepted write.
9
+ */
10
+ export function withExclusiveWrites<S extends object = Record<string, unknown>>(
11
+ registerService: typeof register, names: readonly string[],
12
+ options: { prepare?: (action: string, args: readonly unknown[]) => void; coalesce?: readonly string[]; settle?: (before: S, next: S, live: S) => S } = {},
13
+ ): typeof register {
14
+ return ((name: string, definition: ServiceDefinition<Record<string, unknown>>) => {
15
+ let busy = false;
16
+ let activeAction = "";
17
+ let completion = Promise.resolve();
18
+ let complete = () => {};
19
+ let handle: { getState(): Record<string, unknown>; exclusiveWriteState(next: Record<string, unknown>): Promise<unknown> };
20
+ const wrapped: ServiceDefinition<Record<string, unknown>> = {
21
+ ...definition,
22
+ state: { ...definition.state, writeBusy: false },
23
+ notHydrated: [...(definition.notHydrated ?? []), 'writeBusy'],
24
+ actions: {
25
+ ...Object.fromEntries(Object.entries(definition.actions ?? {}).map(([action, reduce]) => [action,
26
+ names.includes(action) ? async (state: Record<string, unknown>, ...args: never[]) => {
27
+ // Intake request metadata even when its state replacement is skipped.
28
+ options.prepare?.(action, args);
29
+ if (busy) {
30
+ // Repeated initial loads must await the accepted load, so callers
31
+ // observe its committed rows rather than the initial skeleton.
32
+ if (activeAction === action && options.coalesce?.includes(action)) await completion;
33
+ return;
34
+ }
35
+ busy = true;
36
+ activeAction = action;
37
+ completion = new Promise<void>(resolve => { complete = resolve; });
38
+ try {
39
+ await handle.exclusiveWriteState({ ...handle.getState(), writeBusy: true });
40
+ const next = await reduce(state, ...args);
41
+ const live = handle.getState();
42
+ // Non-write actions (for example editing a draft field) can still run
43
+ // during I/O. Let the owning service preserve those newer edits.
44
+ const settled = options.settle ? options.settle(state as S, (next ?? live) as S, live as S) : next ?? live;
45
+ await handle.exclusiveWriteState({ ...settled, writeBusy: false });
46
+ } catch (error) {
47
+ await handle.exclusiveWriteState({ ...handle.getState(), writeBusy: false });
48
+ throw error;
49
+ } finally {
50
+ busy = false;
51
+ complete();
52
+ }
53
+ } : reduce,
54
+ ])),
55
+ exclusiveWriteState: (_state, next: Record<string, unknown>) => next,
56
+ },
57
+ };
58
+ const registered = registerService(name, wrapped);
59
+ // Registration preserves this private action, but the dynamic action map
60
+ // cannot express its payload to the generic service handle.
61
+ handle = registered as unknown as typeof handle;
62
+ // Older hosts ignore notHydrated. A fresh worker has no pending write.
63
+ handle.getState().writeBusy = false;
64
+ return registered;
65
+ }) as typeof register;
66
+ }
@@ -0,0 +1,113 @@
1
+ // The header badge counts (bell, chat, cart) as one service piece, shared by the app-level nav workers that
2
+ // bind them: `himi-branded-lite-nav` (the full nav worker of the Branded Lite app) and `himi-branded-lite-header-badges`
3
+ // (the badges-only worker a scaffold ships). Both name their service `brandedLiteNav`, so a top-bar action binds the
4
+ // same `$service:brandedLiteNav.<field>` path in either.
5
+ //
6
+ // `null` is unavailable and never a zero (see source-badges.ts). The counts refresh at launch, whenever the
7
+ // signed-in identity changes (the native host session clock, or the reserved `onIdentityChange` hook a web host
8
+ // delivers), on every foreground (`onForeground`), and whenever the worker is asked to. A read that finishes after
9
+ // the identity changed, or after a newer read began, is dropped.
10
+ import { hostSessionFromGlobal } from "@himalaya/iap";
11
+ import { readSourceBadges } from "./source-badges.js";
12
+
13
+ export interface HeaderBadgeState {
14
+ notificationsBadge: number | null;
15
+ chatBadge: number | null;
16
+ cartBadge: number | null;
17
+ /** Which counts the last refresh tried and failed to read ("" when it read every count it could). A count that is
18
+ * unavailable by design (a Visitor's bell and chat, offline) is not an error. Diagnostic: it says why a badge is
19
+ * missing, so a migration can be checked. */
20
+ errorText: string;
21
+ }
22
+ export const HEADER_BADGES_INITIAL: HeaderBadgeState = { notificationsBadge: null, chatBadge: null, cartBadge: null, errorText: "" };
23
+
24
+ /** The counts describe THIS run: a snapshot from the last one (the web store persists an app worker's state per
25
+ * account) would show another day's numbers until the first read lands. Declare them `notPersisted` and
26
+ * `notHydrated` on the service. */
27
+ export const HEADER_BADGE_KEYS: ("notificationsBadge" | "chatBadge" | "cartBadge" | "errorText")[] = ["notificationsBadge", "chatBadge", "cartBadge", "errorText"];
28
+
29
+ /** The action signatures a service that uses `headerBadges` declares in its `defineService` generic. */
30
+ // A `type`, not an `interface`: `defineService` constrains its actions to `Record<string, fn>`, which only a type
31
+ // alias satisfies (an interface has no implicit index signature).
32
+ export type HeaderBadgeActionSignatures<S> = {
33
+ /** Re-read the header badge counts. Only the newest read lands. */
34
+ refreshBadges: (s: S) => Promise<S>;
35
+ /** Drop every badge count (a new identity), committed at once so no stale number waits on a network read. */
36
+ dropBadges: (s: S) => Promise<S>;
37
+ /** Reserved lifecycle hooks the app-service host delivers to every service that declares them. */
38
+ onForeground: (s: S) => Promise<S>;
39
+ onIdentityChange: (s: S) => Promise<S>;
40
+ };
41
+
42
+ /** What `headerBadges` hands a worker. Named (not inferred) so a worker can annotate its `badges`, which breaks the
43
+ * loop between that value and the service handle it is built from. */
44
+ export interface HeaderBadges<S> {
45
+ actions: HeaderBadgeActionSignatures<S>;
46
+ /** Call once after `defineService`: the launch read, and the session clock's notifications. */
47
+ start(): void;
48
+ /** Re-read after something that may have changed a count (a notification receipt). */
49
+ refresh(): void;
50
+ }
51
+
52
+ type Update<S> = (s: S, change: (current: S) => Promise<S>) => Promise<S>;
53
+ type Self = () => { refreshBadges(): Promise<unknown>; dropBadges(): Promise<unknown> };
54
+
55
+ /**
56
+ * @param update serializes state changes for the worker, so overlapping actions build on the preceding result
57
+ * @param self the worker's own service handle (read lazily: it does not exist yet when this is called)
58
+ */
59
+ export function headerBadges<S extends HeaderBadgeState>(update: Update<S>, self: Self): HeaderBadges<S> {
60
+ /** Which read is the newest: an older one that finishes later must not overwrite a newer answer. */
61
+ let read = 0;
62
+ /** The host session generation the badges on show were read under. */
63
+ let generation = -1;
64
+ /** The clock the native runtime publishes for the signed-in identity: it names the site the bridge is bound to
65
+ * and notifies on every sign-in, sign-out and member switch. A host without one (web, older binaries) reads a
66
+ * signed-out stub that never notifies. */
67
+ const session = hostSessionFromGlobal();
68
+ const cleared = (current: S): S => ({ ...current, ...HEADER_BADGES_INITIAL });
69
+
70
+ const actions: HeaderBadgeActionSignatures<S> = {
71
+ refreshBadges: async (s) => {
72
+ const mine = ++read;
73
+ const badges = await readSourceBadges(session.current().kind === "member");
74
+ return update(s, async (current) => mine === read
75
+ ? { ...current, notificationsBadge: badges.notifications, chatBadge: badges.chat, cartBadge: badges.cart, errorText: badges.failed.length ? `could not read: ${badges.failed.join(", ")}` : "" }
76
+ : current);
77
+ },
78
+ dropBadges: async (s) => {
79
+ ++read; // a read already in flight belongs to the previous identity
80
+ return update(s, async (current) => cleared(current));
81
+ },
82
+ onForeground: async (s) => update(s, async (current) => current).finally(() => { void self().refreshBadges(); }),
83
+ onIdentityChange: async (s) => {
84
+ ++read;
85
+ const dropped = await update(s, async (current) => cleared(current));
86
+ void self().refreshBadges();
87
+ return dropped;
88
+ },
89
+ };
90
+
91
+ /** A session notification: a new generation is a new identity, so the previous one's numbers go first. */
92
+ async function onSession(): Promise<void> {
93
+ const now = session.current().generation;
94
+ if (now !== generation) {
95
+ generation = now;
96
+ await self().dropBadges();
97
+ }
98
+ await self().refreshBadges();
99
+ }
100
+
101
+ return {
102
+ actions,
103
+ /** Call once after `defineService`: the launch read, and the session clock's notifications. */
104
+ start(): void {
105
+ // Subscribing notifies at once, which is the launch read; a host with no clock needs the explicit one.
106
+ let notified = false;
107
+ session.subscribe(() => { notified = true; void onSession(); });
108
+ if (!notified) void self().refreshBadges();
109
+ },
110
+ /** Re-read after something that may have changed a count (a notification receipt). */
111
+ refresh(): void { void self().refreshBadges(); },
112
+ };
113
+ }
@@ -0,0 +1,57 @@
1
+ // Saved products use the host's durable, app-scoped KV, shared by screen workers.
2
+ // Adapted from Hip Shop; a failed write must never claim that a save succeeded.
3
+ export interface SavedProduct {
4
+ id: string;
5
+ name: string;
6
+ price: string;
7
+ image: string;
8
+ wasPrice?: string;
9
+ swatches?: string[];
10
+ }
11
+ type StorageLike = { getItem(key: string): string | null; setItem(key: string, value: string): void };
12
+ const KEY = "himi-store:saved-products:v1";
13
+ function storage(): StorageLike {
14
+ const host = globalThis as { himalaya?: { storage?: StorageLike }; localStorage?: StorageLike };
15
+ const kv = host.himalaya?.storage ?? host.localStorage;
16
+ if (!kv) throw new Error("Saved-product storage is unavailable");
17
+ return kv;
18
+ }
19
+ export function readSavedProducts(): SavedProduct[] {
20
+ const raw = storage().getItem(KEY);
21
+ if (!raw) return [];
22
+ const parsed: unknown = JSON.parse(raw);
23
+ if (!Array.isArray(parsed)) throw new Error("Invalid saved-product data");
24
+ const rows = new Map<string, SavedProduct>();
25
+ for (const value of parsed) {
26
+ if (!value || typeof value !== "object") continue;
27
+ const row = value as Record<string, unknown>;
28
+ if (typeof row.id !== "string" || !row.id.trim() || typeof row.name !== "string") continue;
29
+ const swatches = Array.isArray(row.swatches)
30
+ ? row.swatches.filter((color): color is string => typeof color === "string" && /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(color)).slice(0, 5)
31
+ : [];
32
+ rows.set(row.id, { id: row.id, name: row.name, price: typeof row.price === "string" ? row.price : "", image: typeof row.image === "string" ? row.image : "",
33
+ ...(typeof row.wasPrice === "string" && row.wasPrice ? { wasPrice: row.wasPrice } : {}), ...(swatches.length ? { swatches } : {}) });
34
+ }
35
+ return [...rows.values()];
36
+ }
37
+ export function isProductSaved(id: string): boolean {
38
+ return readSavedProducts().some(row => row.id === id);
39
+ }
40
+ export function writeSavedProducts(rows: SavedProduct[]): void {
41
+ const kv = storage();
42
+ const value = JSON.stringify(rows);
43
+ kv.setItem(KEY, value);
44
+ // Web hosts may swallow quota/security errors. Confirm the synchronous write
45
+ // before displaying success; a missing/mismatched read is a failed save.
46
+ if (kv.getItem(KEY) !== value) throw new Error("Saved-product write did not persist");
47
+ }
48
+ export function toggleSavedProduct(product: SavedProduct): boolean {
49
+ if (!product.id.trim() || !product.name.trim()) throw new Error("No product to save");
50
+ const rows = readSavedProducts();
51
+ const saved = !rows.some(row => row.id === product.id);
52
+ writeSavedProducts(saved ? [product, ...rows] : rows.filter(row => row.id !== product.id));
53
+ return saved;
54
+ }
55
+ export function removeSavedProduct(id: string): void {
56
+ writeSavedProducts(readSavedProducts().filter(row => row.id !== id));
57
+ }
@@ -0,0 +1,207 @@
1
+ import { defineService, type ServiceDefinition } from "@himalaya/state";
2
+ import { createIapCommerce, type IapCommerce, type IapOrderAdapter } from "@himalaya/iap-checkout";
3
+ import { iapPriceFields, type IapCatalogItem } from "@himalaya/iap";
4
+ import { iapPriceCopy, resetUnhydratedKeysOnOlderRuntime } from "./iap-worker.js";
5
+
6
+ // Presentation only. Checkout, mapping, cache, session and refresh policy stay in the shared flow.
7
+ export function withIapPresentation<S extends object>(options: {
8
+ register?: typeof defineService;
9
+ /** The verticals this screen sells; none for a screen that only shows prices. */
10
+ adapters?: readonly IapOrderAdapter[];
11
+ onCreate?(commerce: IapCommerce): void;
12
+ onContent?(state: S): void;
13
+ items(state: S): IapCatalogItem[];
14
+ /** `resolving` is true while the checkout guard has no answer yet (a cold boot, a refresh): a
15
+ * screen reads it as loading, never as "not allowed". */
16
+ present(state: S, price: (id: string, commercePrice?: string) => string, allowed: (id: string) => boolean, appleIapOrResolving: (id: string) => boolean, resolving: (id: string) => boolean): S;
17
+ contentActions: string[];
18
+ /** Defaults to load/refresh/retry; mutations can explicitly request fresh mapping. */
19
+ forcePriceRefreshActions?: string[];
20
+ concurrentPublishActions?: string[];
21
+ /** Override the commerce factory in focused worker tests. */
22
+ commerceFactory?: typeof createIapCommerce;
23
+ transientKeys: (keyof S & string)[];
24
+ prefix: string;
25
+ }): typeof defineService {
26
+ return ((name: string, definition: ServiceDefinition<S>) => {
27
+ let queuePublish = () => {};
28
+ const commerce = (options.commerceFactory ?? createIapCommerce)({ adapters: options.adapters, onChange: () => queuePublish() });
29
+ options.onCreate?.(commerce);
30
+ let items: IapCatalogItem[] = [];
31
+ let loadedItemsKey = "";
32
+ const settledViews = new Map<string, { commerceDisplayPrice?: string; view: ReturnType<IapCommerce["pricing"]["view"]> }>();
33
+ const forcePriceRefreshActions = new Set(options.forcePriceRefreshActions ?? options.contentActions.filter(action => ["load", "refresh", "retry"].includes(action)));
34
+ let contentVersion = 0;
35
+ let actionVersion = 0;
36
+ let activeActions = 0;
37
+ let activeConcurrentPublishActions = 0;
38
+ let actionWaiters: Array<() => void> = [];
39
+ let publishQueued = false;
40
+ // pollDirective() arms its interval as a side effect. Keep a directive from a
41
+ // projection that loses a commit race so the retry can still publish it.
42
+ let uncommittedPollDirective: ReturnType<IapCommerce["pollDirective"]>;
43
+ let uncommittedPollVersion = 0;
44
+ // The committed state, read when a publish runs. Assigned once the service exists, so the
45
+ // service's own initializer never refers to it.
46
+ let committed: () => S = () => definition.state;
47
+ queuePublish = () => {
48
+ if (publishQueued) return;
49
+ publishQueued = true;
50
+ // Tier-5 workers have no timer globals. A microtask is enough here: if the
51
+ // action that caused the price update is still in flight, iapPublish's
52
+ // action-version check queues another publish after that action commits.
53
+ const publish = () => {
54
+ publishQueued = false;
55
+ void service.iapPublish();
56
+ };
57
+ void Promise.resolve().then(publish);
58
+ };
59
+ const project = (state: S, retainedPoll?: ReturnType<IapCommerce["pollDirective"]>): S => {
60
+ const presentationView = (id: string, commercePrice?: string) => {
61
+ const item = items.find(item => item.reference.id === id);
62
+ const reference = item?.reference ?? { kind: "storesProduct", id };
63
+ const key = `${reference.kind}:${reference.id}`;
64
+ const current = commerce.pricing.view(reference);
65
+ const cached = settledViews.get(key);
66
+ const displayPrice = commercePrice ?? item?.commerceDisplayPrice;
67
+ if (current.route === "resolving" && cached && cached.commerceDisplayPrice === displayPrice) return cached.view;
68
+ if (current.route !== "resolving" && item) settledViews.set(key, { commerceDisplayPrice: item.commerceDisplayPrice, view: current });
69
+ return current;
70
+ };
71
+ const price = (id: string, commercePrice?: string) => {
72
+ const item = items.find(item => item.reference.id === id);
73
+ if (!item) return "";
74
+ const view = presentationView(id, commercePrice);
75
+ if (view.route === "resolving") return iapPriceCopy(options.prefix).loading;
76
+ return view.route === "disabled" || view.route === "regular" ? commercePrice ?? item.commerceDisplayPrice ?? "" : iapPriceFields(view, iapPriceCopy(options.prefix)).priceText;
77
+ };
78
+ const allowed = (id: string) => commerce.pricing.checkoutGuard({ kind: "storesProduct", id }).allowed;
79
+ const resolving = (id: string) => commerce.pricing.checkoutGuard({ kind: "storesProduct", id }).route === "resolving";
80
+ const appleIapOrResolving = (id: string) => ["appleIap", "resolving", "unavailable"].includes(presentationView(id).route);
81
+ // Re-evaluate the cadence first. A checkout can enter/leave due work while a prior
82
+ // projection is waiting to retry; a fresh directive supersedes the retained one.
83
+ const poll = commerce.pollDirective(`${name}.iapPoll`) ?? retainedPoll;
84
+ return { ...options.present(state, price, allowed, appleIapOrResolving, resolving), ...(poll ? { _poll: poll } : {}) };
85
+ };
86
+ const mergeConcurrent = (before: S, next: S, current: S): S => {
87
+ if (current === before) return next;
88
+ const merged = { ...current } as Record<string, unknown>;
89
+ const previous = before as Record<string, unknown>;
90
+ const changed = next as Record<string, unknown>;
91
+ for (const key of new Set([...Object.keys(previous), ...Object.keys(changed)])) {
92
+ if (JSON.stringify(previous[key]) === JSON.stringify(changed[key])) continue;
93
+ if (Object.prototype.hasOwnProperty.call(changed, key)) merged[key] = changed[key];
94
+ else delete merged[key];
95
+ }
96
+ return merged as S;
97
+ };
98
+ const actions = Object.fromEntries(Object.entries(definition.actions ?? {}).map(([action, reduce]) => [action, (state: S, ...args: never[]) => {
99
+ actionVersion++;
100
+ activeActions++;
101
+ const concurrentPublish = options.concurrentPublishActions?.includes(action) ?? false;
102
+ if (concurrentPublish) activeConcurrentPublishActions++;
103
+ const content = options.contentActions.includes(action);
104
+ const version = action === "load" ? ++contentVersion : contentVersion;
105
+ const presentResult = (next: S | undefined) => {
106
+ // scopeLanded is the completion of the active load, not a stale load result. It
107
+ // must publish even if another overlapping onAppear load advanced contentVersion.
108
+ if (!next || (content && action !== "scopeLanded" && version !== contentVersion)) return undefined;
109
+ // A committed read projection supersedes older load results still carrying a skeleton.
110
+ if (action === "readChanged" && definition.readLifecycle) contentVersion++;
111
+ if (content) {
112
+ options.onContent?.(next);
113
+ const nextItems = options.items(next);
114
+ // This is an order-independent identity key, not display text. Default
115
+ // string ordering is deterministic on every worker engine, including QuickJS.
116
+ const nextItemsKey = JSON.stringify(nextItems.map(item => JSON.stringify([item.reference.kind, item.reference.id, item.commerceDisplayPrice]))
117
+ .sort());
118
+ items = nextItems;
119
+ const forcePriceRefresh = forcePriceRefreshActions.has(action);
120
+ if (forcePriceRefresh) settledViews.clear();
121
+ if (nextItemsKey !== loadedItemsKey || forcePriceRefresh) {
122
+ loadedItemsKey = nextItemsKey;
123
+ void commerce.loadPrices(items);
124
+ }
125
+ }
126
+ // Checkout preserves prices published while it ran.
127
+ return project(concurrentPublish ? mergeConcurrent(state, next, committed()) : next);
128
+ };
129
+ const finished = () => {
130
+ activeActions--;
131
+ if (concurrentPublish) activeConcurrentPublishActions--;
132
+ const waiters = actionWaiters;
133
+ actionWaiters = [];
134
+ for (const resolve of waiters) resolve();
135
+ };
136
+ try {
137
+ const next = reduce(state, ...args);
138
+ // A cached read projection must commit before another onAppear can consume it.
139
+ // Other content actions retain their scheduling: shop filters and panels can
140
+ // change while a load is pending, and their existing completion order matters.
141
+ const synchronousReadProjection = action === "readChanged" && !!definition.readLifecycle;
142
+ if ((content && !synchronousReadProjection) || (next && typeof (next as Promise<S | undefined>).then === "function")) {
143
+ return (async () => {
144
+ try { return presentResult(await next); }
145
+ finally { finished(); }
146
+ })();
147
+ }
148
+ const result = presentResult(next as S | undefined);
149
+ finished();
150
+ return result;
151
+ } catch (error) {
152
+ finished();
153
+ throw error;
154
+ }
155
+ }]));
156
+ const service = (options.register ?? defineService)(name, {
157
+ // The collection's shown page goes with the rows and chrome it copies: kept out of the restore with them.
158
+ ...definition, notHydrated: [...(definition.notHydrated ?? []), ...options.transientKeys,
159
+ ...((options.transientKeys as string[]).includes('collection') ? ['collectionShown' as keyof S & string] : [])],
160
+ // Prices land on their own clock, and a commit replaces the whole state — so a publish
161
+ // can carry a snapshot that an in-flight commit (a page that just landed, a tap) has
162
+ // since replaced. Project the state as it is now, and publish only when the prices
163
+ // actually change it: with no App Store mapping, or prices already shown, there is
164
+ // nothing to publish and nothing to overwrite.
165
+ actions: { ...actions, iapPublish: async () => {
166
+ // Checkout actions publish their busy phase while running. Every other action
167
+ // finishes before we take a projection, so it cannot erase a reducer's result.
168
+ for (;;) {
169
+ if (activeActions > activeConcurrentPublishActions) await new Promise<void>(resolve => actionWaiters.push(resolve));
170
+ await Promise.resolve();
171
+ const version = actionVersion;
172
+ await Promise.resolve();
173
+ if (activeActions <= activeConcurrentPublishActions && version === actionVersion) break;
174
+ }
175
+ const current = committed();
176
+ // The runtime commits an action's result just after this wrapper returns. If a
177
+ // scope action lands while prices are being projected, publishing this snapshot
178
+ // would put the older scope back on top. Drop it and retry against the commit.
179
+ const retainedPollVersion = uncommittedPollVersion;
180
+ const retainedPoll = uncommittedPollDirective;
181
+ const next: S & { _poll?: unknown } = project(current, retainedPoll);
182
+ await Promise.resolve();
183
+ if (committed() !== current) {
184
+ // Overlapping retries can race too: a projection with no new directive must
185
+ // not erase one another already retained after pollDirective() armed itself.
186
+ if (next._poll) {
187
+ uncommittedPollDirective = next._poll as ReturnType<IapCommerce["pollDirective"]>;
188
+ uncommittedPollVersion++;
189
+ }
190
+ queuePublish();
191
+ return undefined;
192
+ }
193
+ // Another concurrent projection may have retained a newer directive since this
194
+ // snapshot. Clear only the exact retained generation this successful commit used.
195
+ if (next._poll && retainedPollVersion === uncommittedPollVersion && retainedPoll === uncommittedPollDirective) {
196
+ uncommittedPollDirective = undefined;
197
+ uncommittedPollVersion++;
198
+ }
199
+ return !next._poll && JSON.stringify(next) === JSON.stringify(current) ? undefined : next;
200
+ }, iapPoll: async () => { await commerce.poll(); return undefined; },
201
+ iapRefresh: async () => { await commerce.loadPrices(items); return undefined; } },
202
+ });
203
+ committed = () => (service as unknown as { getState(): S }).getState();
204
+ resetUnhydratedKeysOnOlderRuntime(service, definition.state, options.transientKeys);
205
+ return service;
206
+ }) as unknown as typeof defineService;
207
+ }