@wix/himalaya-cli 0.1647.0 → 0.1649.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 (101) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/builder.d.ts +3 -1
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +4 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/validator.d.ts +6 -0
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/wix-sdk/media/src/rendition.d.ts +6 -0
  5. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +1 -0
  6. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/screens.mjs +4 -0
  7. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +1 -0
  8. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-events.mjs +4 -0
  9. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-media.mjs +22 -4
  10. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-rich-content.mjs +4 -0
  11. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-stores-collections.mjs +4 -0
  12. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-stores.mjs +4 -0
  13. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-video.mjs +4 -0
  14. package/dist/browser-plane/assets.json +5 -5
  15. package/dist/browser-plane/preview-deferred/{155f61519885c85d61a39fa595197071a3ca07680da56055ccb1dcff2e709cd1.bin → 4ef4d326496b4d7809746936207067b4c921f5db9878ecc7030aa3a9e4d2aaeb.bin} +1 -1
  16. package/dist/browser-plane/sw.js +5 -5
  17. package/dist/cli.mjs +4098 -3351
  18. package/dist/preview-assets.generated.bin +0 -0
  19. package/guides/component-reference.json +1 -1
  20. package/guides/component-reference.md +2 -0
  21. package/guides/designing-himi-screens.md +4 -0
  22. package/guides/himi-skill.md +6 -0
  23. package/guides/image-preview.md +92 -0
  24. package/guides/index.json +7 -0
  25. package/guides/release-notes.md +6 -0
  26. package/guides/sdk-reference.json +9 -2
  27. package/package.json +2 -2
  28. package/template-icons/wholesale-store.png +0 -0
  29. package/templates/beauty-salon-owner/dev/index.ts +7 -0
  30. package/templates/community-club-owner/dev/index.ts +7 -0
  31. package/templates/events-meetups-owner/dev/index.ts +7 -0
  32. package/templates/gym-fitness-owner/dev/index.ts +7 -0
  33. package/templates/nonprofit-cause-owner/dev/index.ts +7 -0
  34. package/templates/owner-lite/dev/index.ts +7 -0
  35. package/templates/podcast-creator-owner/dev/index.ts +7 -0
  36. package/templates/portfolio-creative-owner/dev/index.ts +7 -0
  37. package/templates/restaurant-owner/dev/index.ts +7 -0
  38. package/templates/retail-store-owner/dev/index.ts +7 -0
  39. package/templates/wholesale-store/README.md +53 -0
  40. package/templates/wholesale-store/config.ts +247 -0
  41. package/templates/wholesale-store/dev/index.ts +12194 -0
  42. package/templates/wholesale-store/himalaya.content.json +43 -0
  43. package/templates/wholesale-store/himalaya.template.json +14 -0
  44. package/templates/wholesale-store/icon.png +0 -0
  45. package/templates/wholesale-store/platforms.json +1 -0
  46. package/templates/wholesale-store/tier5-src/_shared/app-locale.ts +61 -0
  47. package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +279 -0
  48. package/templates/wholesale-store/tier5-src/_shared/business-chat-copy.ts +40 -0
  49. package/templates/wholesale-store/tier5-src/_shared/business-chat-history.ts +51 -0
  50. package/templates/wholesale-store/tier5-src/_shared/business-chat-message-model.ts +177 -0
  51. package/templates/wholesale-store/tier5-src/_shared/business-chat-model.ts +56 -0
  52. package/templates/wholesale-store/tier5-src/_shared/business-chat-presenter.ts +576 -0
  53. package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +148 -0
  54. package/templates/wholesale-store/tier5-src/_shared/collection-contract.ts +228 -0
  55. package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +194 -0
  56. package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +252 -0
  57. package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +423 -0
  58. package/templates/wholesale-store/tier5-src/_shared/detail-presence.ts +51 -0
  59. package/templates/wholesale-store/tier5-src/_shared/empty-flags.ts +33 -0
  60. package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +508 -0
  61. package/templates/wholesale-store/tier5-src/_shared/exclusive-writes.ts +66 -0
  62. package/templates/wholesale-store/tier5-src/_shared/himi-account.ts +164 -0
  63. package/templates/wholesale-store/tier5-src/_shared/himi-copy.ts +89 -0
  64. package/templates/wholesale-store/tier5-src/_shared/himi-store-categories.ts +108 -0
  65. package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +22 -0
  66. package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +57 -0
  67. package/templates/wholesale-store/tier5-src/_shared/himi-store.ts +7 -0
  68. package/templates/wholesale-store/tier5-src/_shared/himi-text.ts +24 -0
  69. package/templates/wholesale-store/tier5-src/_shared/hosted-checkout.ts +70 -0
  70. package/templates/wholesale-store/tier5-src/_shared/iap-presentation.ts +207 -0
  71. package/templates/wholesale-store/tier5-src/_shared/iap-worker.ts +125 -0
  72. package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +68 -0
  73. package/templates/wholesale-store/tier5-src/_shared/live-session.ts +172 -0
  74. package/templates/wholesale-store/tier5-src/_shared/local-preferences.ts +38 -0
  75. package/templates/wholesale-store/tier5-src/_shared/member-access.ts +52 -0
  76. package/templates/wholesale-store/tier5-src/_shared/member-account-routes.ts +52 -0
  77. package/templates/wholesale-store/tier5-src/_shared/member-orders.ts +8 -0
  78. package/templates/wholesale-store/tier5-src/_shared/member-screen.ts +99 -0
  79. package/templates/wholesale-store/tier5-src/_shared/online-actions.ts +76 -0
  80. package/templates/wholesale-store/tier5-src/_shared/owner-editor-value.ts +164 -0
  81. package/templates/wholesale-store/tier5-src/_shared/owner-load-error.ts +348 -0
  82. package/templates/wholesale-store/tier5-src/_shared/payment-setup.ts +6 -0
  83. package/templates/wholesale-store/tier5-src/_shared/read-service.ts +255 -0
  84. package/templates/wholesale-store/tier5-src/_shared/restaurant-ordering.ts +201 -0
  85. package/templates/wholesale-store/tier5-src/_shared/rich-body.ts +78 -0
  86. package/templates/wholesale-store/tier5-src/_shared/rich-content-link.ts +34 -0
  87. package/templates/wholesale-store/tier5-src/_shared/sign-in-sheet.ts +18 -0
  88. package/templates/wholesale-store/tier5-src/_shared/store-order-presentation.ts +56 -0
  89. package/templates/wholesale-store/tier5-src/_shared/store-product-info.ts +50 -0
  90. package/templates/wholesale-store/tier5-src/business-chat/index.ts +724 -0
  91. package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +602 -0
  92. package/templates/wholesale-store/tier5-src/himi-branded-lite-order/index.ts +472 -0
  93. package/templates/wholesale-store/tier5-src/himi-branded-lite-orders/index.ts +327 -0
  94. package/templates/wholesale-store/tier5-src/himi-store-account/index.ts +998 -0
  95. package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +889 -0
  96. package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +68 -0
  97. package/templates/wholesale-store/tier5-src/himi-store-shop/index.ts +150 -0
  98. package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +507 -0
  99. package/templates/wholesale-store/tier5-src/wix-spaces-collection-detail/index.ts +195 -0
  100. package/templates/wholesale-store/tokens.json +340 -0
  101. package/templates/yoga-studio-owner/dev/index.ts +7 -0
@@ -0,0 +1,164 @@
1
+ import { dispatch } from "@himalaya/dispatch";
2
+ // Relative for node resolution (see himi-store.ts note); rewritten off-repo.
3
+ import { displayName, getMyData, initials, type WixMyData } from "@himalaya/wix-users";
4
+ import { getMyMember } from "@himalaya/wix-members";
5
+ import { wixMediaUrl } from "@himalaya/wix-media";
6
+ import { formatDateMedium, formatWeekdayDateTime } from "../_shared/engine-intl.js";
7
+
8
+ export interface AccountProfile {
9
+ isMember: boolean;
10
+ identityLine: string;
11
+ detailLine: string;
12
+ memberName: string;
13
+ memberEmail: string;
14
+ memberImage: string;
15
+ memberInitials: string;
16
+ hasMemberImage: boolean;
17
+ noMemberImage: boolean;
18
+ }
19
+
20
+ export interface AccountActivityRow {
21
+ id: string;
22
+ title: string;
23
+ subtitle: string;
24
+ meta: string;
25
+ status: string;
26
+ }
27
+
28
+ export function strOf(arg: unknown): string {
29
+ if (typeof arg === "string") return arg;
30
+ const a = arg as { value?: string; text?: string } | undefined;
31
+ return a?.value ?? a?.text ?? "";
32
+ }
33
+
34
+ export function titleCase(value?: string): string {
35
+ return (value || "")
36
+ .toLowerCase()
37
+ .split(/[_\s-]+/)
38
+ .filter(Boolean)
39
+ .map((part) => part[0].toUpperCase() + part.slice(1))
40
+ .join(" ");
41
+ }
42
+
43
+ export function fmtDate(value?: string): string {
44
+ if (!value) return "";
45
+ const date = new Date(value);
46
+ if (Number.isNaN(date.getTime())) return "";
47
+ return formatDateMedium(date);
48
+ }
49
+
50
+ export function fmtDateTime(value?: string): string {
51
+ if (!value) return "";
52
+ const date = new Date(value);
53
+ if (Number.isNaN(date.getTime())) return "";
54
+ return formatWeekdayDateTime(date);
55
+ }
56
+
57
+ function initialsFromName(value: string): string {
58
+ const parts = value.trim().split(/\s+/).filter(Boolean);
59
+ if (!parts.length) return "";
60
+ const first = parts[0]?.[0] ?? "";
61
+ const last = parts.length > 1 ? parts[parts.length - 1]?.[0] ?? "" : "";
62
+ return (first + last).toUpperCase();
63
+ }
64
+
65
+ function profileImage(data: WixMyData): string {
66
+ const profile = data.profile as { profileImage?: string; photo?: { url?: string }; imageUrl?: string } | undefined;
67
+ return profile?.profileImage || profile?.photo?.url || profile?.imageUrl || "";
68
+ }
69
+
70
+ function profileFromData(data: WixMyData, fallbackEmail = ""): AccountProfile {
71
+ const email = fallbackEmail || data.email || data.contactEmail || "";
72
+ const name = displayName(data) || email || "Member";
73
+ const image = profileImage(data);
74
+ return {
75
+ isMember: true,
76
+ identityLine: "Signed in",
77
+ detailLine: email || name,
78
+ memberName: name,
79
+ memberEmail: email,
80
+ memberImage: image,
81
+ memberInitials: initials(data) || initialsFromName(name) || "M",
82
+ hasMemberImage: !!image,
83
+ noMemberImage: !image,
84
+ };
85
+ }
86
+
87
+ /** The signed-in site member's name and photo from their member record, or undefined when it
88
+ * cannot be read or names nobody (the caller then shows the email). */
89
+ async function siteMemberProfile(email: string): Promise<AccountProfile | undefined> {
90
+ try {
91
+ const member = (await getMyMember({ fieldsets: ["FULL"] }))?.member;
92
+ const name = [member?.contact?.firstName, member?.contact?.lastName].map((part) => (part ?? "").trim()).filter(Boolean).join(" ")
93
+ || (member?.profile?.nickname ?? "").trim();
94
+ if (!name) return undefined;
95
+ const image = wixMediaUrl(member?.profile?.photo?.url) || wixMediaUrl(member?.profile?.photo?.id) || "";
96
+ return {
97
+ isMember: true,
98
+ identityLine: "Signed in",
99
+ detailLine: email || name,
100
+ memberName: name,
101
+ memberEmail: email || member?.loginEmail || "",
102
+ memberImage: image,
103
+ memberInitials: initialsFromName(name) || "M",
104
+ hasMemberImage: !!image,
105
+ noMemberImage: !image,
106
+ };
107
+ } catch {
108
+ return undefined;
109
+ }
110
+ }
111
+
112
+ export function guestProfile(detailLine: string): AccountProfile {
113
+ return {
114
+ isMember: false,
115
+ identityLine: "Browsing as a guest",
116
+ detailLine,
117
+ memberName: "",
118
+ memberEmail: "",
119
+ memberImage: "",
120
+ memberInitials: "M",
121
+ hasMemberImage: false,
122
+ noMemberImage: true,
123
+ };
124
+ }
125
+
126
+ export async function signedInEmail(): Promise<string> {
127
+ try {
128
+ const identity = await dispatch("himi.wix.memberIdentity") as unknown;
129
+ const direct = identity as { email?: unknown } | null;
130
+ const wrapped = identity as { payload?: { email?: unknown } } | null;
131
+ const email = direct?.email ?? wrapped?.payload?.email;
132
+ return typeof email === "string" ? email : "";
133
+ } catch {
134
+ return "";
135
+ }
136
+ }
137
+
138
+ export async function loadMemberProfile(guestDetailLine: string): Promise<AccountProfile> {
139
+ // `himi.wix.memberIdentity` is the session source of truth. Visitor-scoped
140
+ // getMyData can still return a site/account nickname (e.g. apptestercoowner)
141
+ // after sign-out or for anonymous — never treat that as a signed-in member.
142
+ const storedEmail = await signedInEmail();
143
+ if (!storedEmail) return guestProfile(guestDetailLine);
144
+ try {
145
+ const data = await getMyData();
146
+ return profileFromData(data, storedEmail);
147
+ } catch {
148
+ // The account profile is an owner endpoint: the web host refuses it, and a site member need
149
+ // not have one. The member's own record (the Members API) still names them.
150
+ const member = await siteMemberProfile(storedEmail);
151
+ if (member) return member;
152
+ return {
153
+ isMember: true,
154
+ identityLine: "Signed in",
155
+ detailLine: storedEmail,
156
+ memberName: storedEmail,
157
+ memberEmail: storedEmail,
158
+ memberImage: "",
159
+ memberInitials: initialsFromName(storedEmail) || "M",
160
+ hasMemberImage: false,
161
+ noMemberImage: true,
162
+ };
163
+ }
164
+ }
@@ -0,0 +1,89 @@
1
+ // Copy-as-configuration for WORKER-emitted strings (`himi docs designing-himi-screens`,
2
+ // §"Copy is configuration"): a worker never hardcodes user-facing copy — the
3
+ // descriptor bakes the provisioned copy-pack overrides relevant to this worker
4
+ // into its onAppear action params as a `copy` JSON object (customer strings or
5
+ // source-matched stock translations, computed at descriptor-build time), and the
6
+ // worker reads every user-facing string through `copyParam(key, fallback)`.
7
+ //
8
+ // STASHED (the stashed appear-params idiom, himi-branded-lite-home): the
9
+ // param-carrying onAppear dispatch updates the stash; later arg-less calls
10
+ // (self-kick refreshes, retry buttons, pull-to-refresh) fall back to it, so
11
+ // resolution order can never drop the pack. With no pack the param is absent
12
+ // and every read returns `fallback` verbatim — routing a worker string through
13
+ // copyParam is byte-for-byte behavior-preserving.
14
+ //
15
+ // Pure + Hermes-safe (no host globals, no Node APIs; its only import is the pure `app-locale` sibling): bundled into
16
+ // every worker that emits user-facing copy, and copied verbatim into the
17
+ // generated templates' tier5-src/_shared/.
18
+
19
+ import { isSingular, setAppLocale, setBusinessTimeZone } from "./app-locale.js";
20
+
21
+ /** Customer strings override every read; translated stock is valid only for its
22
+ * original English fallback. Some existing keys serve more than one message. */
23
+ export type CopyPackValue = string | { source: string; translation: string };
24
+
25
+ let stashedCopy: Record<string, CopyPackValue> = Object.create(null);
26
+ let copyReceived = false;
27
+
28
+ /** Absorb the `copy` onAppear param (customer strings or stock translation records)
29
+ * from an action arg. Call first in every action that can receive onAppear
30
+ * params (load/refresh). Non-copy args and malformed packs are ignored — the
31
+ * stock fallbacks keep rendering. */
32
+ export function stashCopy(arg: unknown): void {
33
+ if (!arg || typeof arg !== "object") return;
34
+ // A param-carrying dispatch names the app language and business zone too (absent: the English house
35
+ // pattern, and no zone).
36
+ if ("copy" in arg || "locale" in arg || "businessTimeZone" in arg) {
37
+ setAppLocale((arg as Record<string, unknown>).locale);
38
+ setBusinessTimeZone((arg as Record<string, unknown>).businessTimeZone);
39
+ }
40
+ const raw = (arg as Record<string, unknown>).copy;
41
+ if (typeof raw !== "string" || !raw) return;
42
+ try {
43
+ const parsed = JSON.parse(raw) as unknown;
44
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
45
+ const next: Record<string, CopyPackValue> = Object.create(null);
46
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
47
+ if (typeof value === "string") next[key] = value;
48
+ else if (value && typeof value === "object" && !Array.isArray(value)) {
49
+ const row = value as Record<string, unknown>;
50
+ if (typeof row.source === "string" && typeof row.translation === "string") {
51
+ next[key] = { source: row.source, translation: row.translation };
52
+ }
53
+ }
54
+ }
55
+ stashedCopy = next;
56
+ copyReceived = true;
57
+ } catch {
58
+ // Malformed pack param — keep the stock copy rather than dying mid-action.
59
+ }
60
+ }
61
+
62
+ /** The provisioned override for `key`, or `fallback` (the stock copy). An optional
63
+ * restored label survives only until a current copy pack arrives. */
64
+ export function copyParam(key: string, fallback: string, restoredFallback = fallback): string {
65
+ const value = stashedCopy[key];
66
+ // A disk-restored row may paint before onAppear supplies its copy pack. Keep its
67
+ // last label only before a pack arrives; even an empty current pack selects stock copy.
68
+ if (value === undefined) return copyReceived ? fallback : restoredFallback;
69
+ if (typeof value === "string") return value !== "" ? value : fallback;
70
+ return value?.source === fallback && value.translation !== "" ? value.translation : fallback;
71
+ }
72
+
73
+ /** Interpolate `{name}` placeholders in a (possibly overridden) template:
74
+ * `copyTemplate("plans.joinOnSite", "…join {name}.", { name })`. Unknown
75
+ * placeholders resolve to "" so a typo'd override degrades, never crashes. */
76
+ export function copyTemplate(key: string, fallback: string, values: Record<string, string | number>): string {
77
+ return copyParam(key, fallback).replace(/\{([A-Za-z0-9_]+)\}/g, (_all, name: string) =>
78
+ name in values ? String(values[name]) : "",
79
+ );
80
+ }
81
+
82
+ /** The small ICU plural form used by Bookings spot counts. The provisioned copy may
83
+ * translate both branches without adding a second key for the singular. */
84
+ export function copyPlural(key: string, fallback: string, count: number): string {
85
+ const pattern = copyParam(key, fallback);
86
+ const match = /^\{n, plural, one \{([^{}]*)\} other \{([^{}]*)\}\}$/.exec(pattern);
87
+ if (!match) return copyTemplate(key, fallback, { n: count });
88
+ return (isSingular(count) ? match[1] : match[2])!.replace(/#/g, String(count));
89
+ }
@@ -0,0 +1,108 @@
1
+ // Store categories for the Branded Lite Shop chip row and the Home "Shop by category"
2
+ // rail — one reader, so both list the same categories in the same order.
3
+ //
4
+ // Catalog V3 Categories first, V1 collections only when V3 THROWS (a legacy V1 site):
5
+ // a V3 success with zero rows is an empty catalogue, and V1 on a V3 site answers 428.
6
+ // Same rule as wix-spaces-collections; see the reasoning there.
7
+ import { categoryCount, categoryImage, queryCollections, queryStoreCategories, type StoreCategoriesResponse, type StoreCategory, type WixCollection } from "@himalaya/wix-stores-collections";
8
+ import { wixMediaUrl } from "@himalaya/wix-media";
9
+
10
+ export interface StoreCategoryCard {
11
+ id: string;
12
+ name: string;
13
+ image: string;
14
+ hasImage: boolean;
15
+ noImage: boolean;
16
+ subtitle?: string;
17
+ }
18
+
19
+ /** "All Products" is a Wix system collection — every product is in it, so it is
20
+ * the Shop's own "All" chip, not a category a shopper picks. */
21
+ const SYSTEM_NAMES = ["all products"];
22
+ const SYSTEM_COLLECTION_IDS = ["00000000-000000-000000-000000000001"];
23
+
24
+ function card(id: string, name: string, image: string, subtitle = ""): StoreCategoryCard {
25
+ return { id, name, image, hasImage: !!image, noImage: !image, subtitle };
26
+ }
27
+
28
+ function fromCategory(c: StoreCategory): StoreCategoryCard {
29
+ return card(c.id ?? "", (c.name ?? "").trim(), categoryImage(c), categoryCount(c));
30
+ }
31
+
32
+ function fromCollection(c: WixCollection): StoreCategoryCard {
33
+ const raw = c as unknown as { id?: string; name?: string; media?: { mainMedia?: { image?: { url?: string }; thumbnail?: { url?: string } } } };
34
+ const media = raw.media?.mainMedia;
35
+ return card(raw.id ?? "", (raw.name ?? "").trim(), wixMediaUrl(media?.image?.url ?? media?.thumbnail?.url ?? ""));
36
+ }
37
+
38
+ function visible(rows: StoreCategoryCard[], includeAllProducts = false): StoreCategoryCard[] {
39
+ const seen = new Set<string>();
40
+ return rows.filter((r) => {
41
+ if (!r.id || !r.name || (!includeAllProducts && (SYSTEM_COLLECTION_IDS.includes(r.id) || SYSTEM_NAMES.includes(r.name.toLowerCase()))) || seen.has(r.id)) return false;
42
+ seen.add(r.id);
43
+ return true;
44
+ }).map(row => {
45
+ // Counts belong to the directory opt-in; Home rails and Shop chips retain their
46
+ // established five-field card contract.
47
+ const { subtitle, ...card } = row;
48
+ return includeAllProducts ? row : card;
49
+ });
50
+ }
51
+
52
+ const PAGE_SIZE = 50;
53
+ const MAX_PAGES = 100;
54
+
55
+ async function loadLegacyCategories(includeAllProducts: boolean): Promise<StoreCategoryCard[]> {
56
+ const cards: StoreCategoryCard[] = [];
57
+ const seen = new Set<string>();
58
+ let offset = 0;
59
+ let total: number | undefined;
60
+ for (let page = 0; page < MAX_PAGES; page++) {
61
+ const r = await queryCollections({ query: { paging: { limit: PAGE_SIZE, offset } } });
62
+ const rows = r.collections ?? [];
63
+ const reportedTotal = r.totalResults ?? r.metadata?.total;
64
+ if (reportedTotal != null) total = Math.max(total ?? 0, reportedTotal);
65
+ if (!rows.length) {
66
+ if (total != null && seen.size < total) throw new Error("Category pagination is incomplete");
67
+ return visible(cards, includeAllProducts);
68
+ }
69
+ const priorCount = seen.size;
70
+ rows.forEach(row => { if (row.id) seen.add(row.id); });
71
+ if (page > 0 && seen.size === priorCount) throw new Error("Category pagination made no progress");
72
+ cards.push(...rows.filter(c => c.visible !== false).map(fromCollection));
73
+ offset += rows.length;
74
+ if (total != null ? offset >= total : rows.length < PAGE_SIZE) {
75
+ if (total != null && seen.size < total) throw new Error("Category pagination is incomplete");
76
+ return visible(cards, includeAllProducts);
77
+ }
78
+ }
79
+ throw new Error("Category pagination exceeded the page limit");
80
+ }
81
+
82
+ /** The store's browsable categories in site order. Rejects incomplete reads so callers
83
+ * can retain their last good catalog instead of invalidating a later category. */
84
+ export async function loadStoreCategories({ includeAllProducts = false }: { includeAllProducts?: boolean } = {}): Promise<StoreCategoryCard[]> {
85
+ let r: StoreCategoriesResponse;
86
+ try {
87
+ r = await queryStoreCategories(PAGE_SIZE);
88
+ } catch { return loadLegacyCategories(includeAllProducts); /* Only the initial failure can identify a legacy V1 site. */ }
89
+ const cards: StoreCategoryCard[] = [];
90
+ const cursors = new Set<string>();
91
+ const seen = new Set<string>();
92
+ let total = 0;
93
+ for (let page = 0; page < MAX_PAGES; page++) {
94
+ const categories = r.categories ?? [];
95
+ categories.forEach(c => { if (c.id) seen.add(c.id); });
96
+ total = Math.max(total, r.pagingMetadata?.total ?? 0);
97
+ cards.push(...categories.filter(c => c.visible !== false).map(fromCategory));
98
+ const next = r.pagingMetadata?.cursors?.next;
99
+ if (!next) {
100
+ if (seen.size < total) throw new Error("Category pagination is incomplete");
101
+ return visible(cards, includeAllProducts);
102
+ }
103
+ if (cursors.has(next)) throw new Error("Category pagination repeated a cursor");
104
+ cursors.add(next);
105
+ if (page + 1 < MAX_PAGES) r = await queryStoreCategories(PAGE_SIZE, next);
106
+ }
107
+ throw new Error("Category pagination exceeded the page limit");
108
+ }
@@ -0,0 +1,22 @@
1
+ import { withCollectionSaving, type CollectionSaving } from './collection-service.js';
2
+ import { readSavedProducts, writeSavedProducts } from './himi-store-saved.js';
3
+
4
+ export const storeCollectionSaving: CollectionSaving = {
5
+ read: () => readSavedProducts().map(row => row.id),
6
+ write(ids, rows) {
7
+ const products = new Map(readSavedProducts().map(row => [row.id, row]));
8
+ for (const row of rows) {
9
+ if (typeof row.id !== 'string' || typeof row.name !== 'string') continue;
10
+ const previous = products.get(row.id);
11
+ const freshPrice = typeof row.commercePrice === 'string' ? row.commercePrice : typeof row.subtitle === 'string' ? row.subtitle : '';
12
+ const wasPrice = typeof row.wasPrice === 'string' ? row.wasPrice || undefined : previous?.price === freshPrice ? previous?.wasPrice : undefined;
13
+ products.set(row.id, { ...previous, wasPrice, id: row.id, name: row.name,
14
+ price: freshPrice || previous?.price || '',
15
+ image: typeof row.image === 'string' && row.image ? row.image : previous?.image ?? '' });
16
+ }
17
+ const selected = ids.map(id => products.get(id));
18
+ if (selected.some(row => !row)) throw new Error('Saved product metadata is unavailable');
19
+ writeSavedProducts(selected.filter((row): row is NonNullable<typeof row> => !!row));
20
+ },
21
+ };
22
+ export const defineService = withCollectionSaving(storeCollectionSaving);
@@ -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,7 @@
1
+ // Graduated to the SDK (SP-3): the store display helpers + v3 product query now live in
2
+ // @himalaya/wix-stores. This thin re-export keeps existing bundle imports working; new
3
+ // code should import from "@himalaya/wix-stores" directly.
4
+ // Relative so node (tests importing worker sources) resolves it too — the bare
5
+ // "@himalaya/wix-stores" name exists only in the esbuild alias map / the off-repo
6
+ // umbrella. gen-templates.mts rewrites this back to @himalaya/wix-stores off-repo.
7
+ export * from "@himalaya/wix-stores";
@@ -0,0 +1,24 @@
1
+ // Shared display-text helpers for himi cards: trim catalog artifacts from titles and
2
+ // derive up-to-two-letter placeholder initials so same-first-letter lists still vary.
3
+
4
+ /** Trim trailing artifact markers (stray asterisks / footnote daggers) and whitespace
5
+ * that leak from test/seed catalogs, without touching interior punctuation. Falls back
6
+ * to the original when trimming would empty the string. */
7
+ export function cleanTitle(value?: string): string {
8
+ const raw = (value ?? "").trim();
9
+ const cleaned = raw.replace(/[\s*†‡]+$/u, "").trim();
10
+ return cleaned || raw;
11
+ }
12
+
13
+ /** Up to two significant initials for a placeholder avatar. Two-plus words → first
14
+ * letter of the first two; a single word → its first two alphanumerics. Keeps a list
15
+ * of similar names (e.g. many "Booking…") from collapsing to one identical glyph. */
16
+ export function initials(value?: string): string {
17
+ const words = (value ?? "").trim().split(/\s+/).filter(Boolean);
18
+ if (words.length === 0) return "#";
19
+ if (words.length === 1) {
20
+ const alnum = words[0].replace(/[^\p{L}\p{N}]/gu, "");
21
+ return (alnum.slice(0, 2) || "#").toUpperCase();
22
+ }
23
+ return ((words[0][0] ?? "") + (words[1][0] ?? "")).toUpperCase();
24
+ }
@@ -0,0 +1,70 @@
1
+ // Hosted checkout. A Branded Lite hosted in a host shell (Spaces) pays as the member the host
2
+ // lent it: Headless `createRedirectSession` does not take a Member instance, so the HOST opens the site's
3
+ // checkout signed in as that member. The worker names only its ecom checkout; the host reads Wix's
4
+ // checkout URL, mints a one-time member session and opens the site's `createSessionCookie` → checkout.
5
+ // The session token never reaches this worker.
6
+ //
7
+ // Classic Wix Events tickets and classic Pricing Plans have no ecom checkout: for those the
8
+ // worker names the page by id (`himi.host.memberSitePage`) and the host opens the site's own event or
9
+ // plans page the same way, signed in — where the member picks and pays on the site. A member's orders
10
+ // are the same (Wix lists them to no member identity), so My orders opens the site's own page too.
11
+
12
+ import { dispatch } from "@himalaya/dispatch";
13
+ import { hostSiteFromInput } from "./branded-lite-hosted.js";
14
+
15
+ /** The host verbs (registered by the host shell, never by the app itself). The first prepares the
16
+ * checkout and answers a one-time ticket; the second opens it. Two steps so the caller's charge guard
17
+ * is re-read after the host's network round trips and right before the checkout opens — the prepared
18
+ * URL (which carries the member's session token) stays in the host; only the ticket crosses here. */
19
+ export const HOSTED_CHECKOUT_ACTION = "himi.host.memberCheckout";
20
+ export const HOSTED_CHECKOUT_OPEN_ACTION = "himi.host.memberCheckout.open";
21
+ /** Prepares a site PAGE (not an ecom checkout) the same way; opened with [HOSTED_CHECKOUT_OPEN_ACTION]. */
22
+ export const HOSTED_SITE_PAGE_ACTION = "himi.host.memberSitePage";
23
+
24
+ /** A site page a hosted worker may ask its host for — ids only, never a URL: the host reads the URL
25
+ * from Wix itself and decides whether the member may be signed in there. */
26
+ export type HostedSitePage = { page: "event"; eventId: string } | { page: "plans"; planId?: string } | { page: "orders" };
27
+
28
+ /** Whether this worker runs inside a host that opened a site for it. */
29
+ export function isHostedWorker(): boolean {
30
+ return hostSiteFromInput((globalThis as { himalaya?: { input?: unknown } }).himalaya?.input) !== null;
31
+ }
32
+
33
+ type HostAnswer = { opened?: unknown; ticket?: unknown; payload?: { opened?: unknown; ticket?: unknown } } | null;
34
+ type HostOpener = (stillMayCharge: () => Promise<boolean>) => Promise<boolean | "withdrawn">;
35
+
36
+ /** Prepare with [action] [params] → re-read the guard → open by ticket. A host without the verbs, or one
37
+ * that refused (Wix named no page, an unsafe URL, no account session), → false, never a throw. */
38
+ function hostOpener(action: string, params: Record<string, string>): HostOpener {
39
+ return async (stillMayCharge) => {
40
+ try {
41
+ const prepared = await dispatch(action, params) as HostAnswer;
42
+ const ticket = prepared?.ticket ?? prepared?.payload?.ticket;
43
+ if (typeof ticket !== "string" || !ticket) return false;
44
+ // An unopened ticket simply expires in the host: nothing to cancel.
45
+ if (!(await stillMayCharge())) return "withdrawn";
46
+ const result = await dispatch(HOSTED_CHECKOUT_OPEN_ACTION, { ticket }) as HostAnswer;
47
+ const opened = result?.opened ?? result?.payload?.opened;
48
+ return opened === true || opened === "true";
49
+ } catch {
50
+ return false;
51
+ }
52
+ };
53
+ }
54
+
55
+ /** `payCashierOrder`'s `openCashier` for a hosted app: the host prepares [checkoutId]'s checkout as the
56
+ * lent member, the caller's guard is re-read, and only then does the host open it. Resolves whether it
57
+ * opened ("withdrawn" when the guard said no); a host without the verbs (or that refused) → false. */
58
+ export function hostedCheckoutOpener(checkoutId: string): HostOpener {
59
+ return hostOpener(HOSTED_CHECKOUT_ACTION, { checkoutId });
60
+ }
61
+
62
+ /** The site's own [page] opened by the host, signed in as the lent member where the host deems it safe
63
+ * (a visitor otherwise) — the same two steps and answers as [hostedCheckoutOpener]. */
64
+ export function hostedSitePageOpener(page: HostedSitePage): HostOpener {
65
+ const params: Record<string, string> = page.page === "event"
66
+ ? { page: "event", eventId: page.eventId }
67
+ : page.page === "orders" ? { page: "orders" }
68
+ : { page: "plans", ...(page.planId ? { planId: page.planId } : {}) };
69
+ return hostOpener(HOSTED_SITE_PAGE_ACTION, params);
70
+ }