@wix/himalaya-cli 0.1748.0 → 0.1749.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 (170) hide show
  1. package/bin/himi +16 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/builder.d.ts +3 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +9 -0
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/l10n.mjs +1 -1
  5. package/dist/browser-plane/assets.json +7 -7
  6. package/dist/browser-plane/preview-deferred/{63821bbb8f637899037252154a5587f0596e4b537173c7f50551f9e44f7c22c0.bin → b40ea5d0d6251898ff5617139fde8be008dd11e99a70b14c1052093685401700.bin} +1 -1
  7. package/dist/browser-plane/sw.js +6 -6
  8. package/dist/browser-plane/t5-frame.html +1 -1
  9. package/dist/browser-plane/t5-worker-frame.html +1 -1
  10. package/dist/cli.mjs +118 -67
  11. package/dist/preview-assets.generated.bin +0 -0
  12. package/guides/component-reference.json +1 -1
  13. package/guides/component-reference.md +9 -0
  14. package/package.json +2 -2
  15. package/template-icons/medical-services.png +0 -0
  16. package/templates/beauty-salon/dev/index.ts +1 -0
  17. package/templates/beauty-salon/l10n/en.json +6 -0
  18. package/templates/beauty-salon/l10n/fr.json +11 -0
  19. package/templates/beauty-salon/l10n/he.json +9 -0
  20. package/templates/beauty-salon/tier5-src/_shared/member-bookings.ts +17 -4
  21. package/templates/beauty-salon/tier5-src/_shared/staff-name.ts +18 -0
  22. package/templates/beauty-salon/tier5-src/himi-booking-bookings/index.ts +6 -2
  23. package/templates/beauty-salon/tier5-src/himi-booking-service/index.ts +7 -2
  24. package/templates/beauty-salon/tier5-src/himi-booking-time/index.ts +6 -4
  25. package/templates/beauty-salon-owner/dev/index.ts +54 -0
  26. package/templates/beauty-salon-owner/tier5-src/_shared/aria-chat.ts +30 -4
  27. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  28. package/templates/branded-lite/dev/index.ts +1 -0
  29. package/templates/branded-lite/l10n/fr.json +5 -0
  30. package/templates/branded-lite/l10n/he.json +4 -0
  31. package/templates/branded-lite/tier5-src/_shared/member-bookings.ts +17 -4
  32. package/templates/branded-lite/tier5-src/_shared/staff-name.ts +18 -0
  33. package/templates/branded-lite/tier5-src/himi-booking-bookings/index.ts +6 -2
  34. package/templates/branded-lite/tier5-src/himi-booking-service/index.ts +7 -2
  35. package/templates/branded-lite/tier5-src/himi-booking-time/index.ts +6 -4
  36. package/templates/community-club/dev/index.ts +1 -0
  37. package/templates/community-club/tier5-src/_shared/member-bookings.ts +17 -4
  38. package/templates/community-club-owner/dev/index.ts +54 -0
  39. package/templates/community-club-owner/tier5-src/_shared/aria-chat.ts +30 -4
  40. package/templates/community-club-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  41. package/templates/conference/dev/index.ts +1 -0
  42. package/templates/events-meetups/dev/index.ts +1 -0
  43. package/templates/events-meetups/tier5-src/_shared/member-bookings.ts +17 -4
  44. package/templates/events-meetups-owner/dev/index.ts +54 -0
  45. package/templates/events-meetups-owner/tier5-src/_shared/aria-chat.ts +30 -4
  46. package/templates/events-meetups-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  47. package/templates/gym-fitness/dev/index.ts +1 -0
  48. package/templates/gym-fitness/l10n/en.json +6 -0
  49. package/templates/gym-fitness/l10n/fr.json +11 -0
  50. package/templates/gym-fitness/l10n/he.json +9 -0
  51. package/templates/gym-fitness/tier5-src/_shared/member-bookings.ts +17 -4
  52. package/templates/gym-fitness/tier5-src/_shared/staff-name.ts +18 -0
  53. package/templates/gym-fitness/tier5-src/himi-booking-bookings/index.ts +6 -2
  54. package/templates/gym-fitness/tier5-src/himi-booking-service/index.ts +7 -2
  55. package/templates/gym-fitness/tier5-src/himi-booking-time/index.ts +6 -4
  56. package/templates/gym-fitness-owner/dev/index.ts +54 -0
  57. package/templates/gym-fitness-owner/tier5-src/_shared/aria-chat.ts +30 -4
  58. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  59. package/templates/medical-services/README.md +53 -0
  60. package/templates/medical-services/config.ts +320 -0
  61. package/templates/medical-services/dev/index.ts +17783 -0
  62. package/templates/medical-services/himalaya.content.json +46 -0
  63. package/templates/medical-services/himalaya.template.json +14 -0
  64. package/templates/medical-services/icon.png +0 -0
  65. package/templates/medical-services/platforms.json +1 -0
  66. package/templates/medical-services/tier5-src/_shared/app-locale.ts +61 -0
  67. package/templates/medical-services/tier5-src/_shared/booking-location.ts +147 -0
  68. package/templates/medical-services/tier5-src/_shared/booking-session.ts +222 -0
  69. package/templates/medical-services/tier5-src/_shared/branded-lite-hosted.ts +280 -0
  70. package/templates/medical-services/tier5-src/_shared/branded-load-state.ts +109 -0
  71. package/templates/medical-services/tier5-src/_shared/business-chat-copy.ts +40 -0
  72. package/templates/medical-services/tier5-src/_shared/business-chat-history.ts +51 -0
  73. package/templates/medical-services/tier5-src/_shared/business-chat-message-model.ts +177 -0
  74. package/templates/medical-services/tier5-src/_shared/business-chat-model.ts +56 -0
  75. package/templates/medical-services/tier5-src/_shared/business-chat-presenter.ts +576 -0
  76. package/templates/medical-services/tier5-src/_shared/business-chat-transport.ts +148 -0
  77. package/templates/medical-services/tier5-src/_shared/collection-contract.ts +228 -0
  78. package/templates/medical-services/tier5-src/_shared/collection-query.ts +193 -0
  79. package/templates/medical-services/tier5-src/_shared/collection-service.ts +400 -0
  80. package/templates/medical-services/tier5-src/_shared/engine-intl.ts +523 -0
  81. package/templates/medical-services/tier5-src/_shared/faq-list.ts +405 -0
  82. package/templates/medical-services/tier5-src/_shared/himi-account.ts +194 -0
  83. package/templates/medical-services/tier5-src/_shared/himi-booking-saved.ts +88 -0
  84. package/templates/medical-services/tier5-src/_shared/himi-bookings.ts +318 -0
  85. package/templates/medical-services/tier5-src/_shared/himi-copy.ts +116 -0
  86. package/templates/medical-services/tier5-src/_shared/himi-store.ts +7 -0
  87. package/templates/medical-services/tier5-src/_shared/himi-text.ts +24 -0
  88. package/templates/medical-services/tier5-src/_shared/host-events.ts +66 -0
  89. package/templates/medical-services/tier5-src/_shared/hosted-checkout.ts +70 -0
  90. package/templates/medical-services/tier5-src/_shared/iap-attendance-form.ts +106 -0
  91. package/templates/medical-services/tier5-src/_shared/iap-attendance-purchase.ts +216 -0
  92. package/templates/medical-services/tier5-src/_shared/iap-attendance.ts +38 -0
  93. package/templates/medical-services/tier5-src/_shared/iap-worker.ts +127 -0
  94. package/templates/medical-services/tier5-src/_shared/inbox-rooms.ts +68 -0
  95. package/templates/medical-services/tier5-src/_shared/local-preferences.ts +38 -0
  96. package/templates/medical-services/tier5-src/_shared/member-access.ts +52 -0
  97. package/templates/medical-services/tier5-src/_shared/member-account-routes.ts +52 -0
  98. package/templates/medical-services/tier5-src/_shared/member-bookings.ts +107 -0
  99. package/templates/medical-services/tier5-src/_shared/member-screen.ts +99 -0
  100. package/templates/medical-services/tier5-src/_shared/notification-target.ts +141 -0
  101. package/templates/medical-services/tier5-src/_shared/offset-page.ts +10 -0
  102. package/templates/medical-services/tier5-src/_shared/online-actions.ts +76 -0
  103. package/templates/medical-services/tier5-src/_shared/owner-load-error.ts +348 -0
  104. package/templates/medical-services/tier5-src/_shared/payment-setup.ts +6 -0
  105. package/templates/medical-services/tier5-src/_shared/rich-body.ts +78 -0
  106. package/templates/medical-services/tier5-src/_shared/rich-content-link.ts +34 -0
  107. package/templates/medical-services/tier5-src/_shared/sign-in-sheet.ts +18 -0
  108. package/templates/medical-services/tier5-src/_shared/staff-name.ts +18 -0
  109. package/templates/medical-services/tier5-src/_shared/weekly-goal.ts +107 -0
  110. package/templates/medical-services/tier5-src/_shared/wix-bi.ts +85 -0
  111. package/templates/medical-services/tier5-src/_shared/wix-member-links.ts +114 -0
  112. package/templates/medical-services/tier5-src/_shared/wix-service-price.ts +146 -0
  113. package/templates/medical-services/tier5-src/business-chat/index.ts +732 -0
  114. package/templates/medical-services/tier5-src/himi-booking-account/index.ts +252 -0
  115. package/templates/medical-services/tier5-src/himi-booking-bookings/index.ts +468 -0
  116. package/templates/medical-services/tier5-src/himi-booking-service/index.ts +1190 -0
  117. package/templates/medical-services/tier5-src/himi-booking-services/index.ts +791 -0
  118. package/templates/medical-services/tier5-src/himi-booking-time/index.ts +1729 -0
  119. package/templates/medical-services/tier5-src/himi-branded-lite-faq/index.ts +6 -0
  120. package/templates/medical-services/tier5-src/himi-branded-lite-notifications/index.ts +256 -0
  121. package/templates/medical-services/tier5-src/himi-clinic-home/index.ts +389 -0
  122. package/templates/medical-services/tier5-src/himi-store-account/index.ts +998 -0
  123. package/templates/medical-services/tokens.json +418 -0
  124. package/templates/nonprofit-cause/dev/index.ts +1 -0
  125. package/templates/nonprofit-cause/tier5-src/_shared/member-bookings.ts +17 -4
  126. package/templates/nonprofit-cause-owner/dev/index.ts +54 -0
  127. package/templates/nonprofit-cause-owner/tier5-src/_shared/aria-chat.ts +30 -4
  128. package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  129. package/templates/owner-lite/dev/index.ts +54 -0
  130. package/templates/owner-lite/tier5-src/_shared/aria-chat.ts +30 -4
  131. package/templates/owner-lite/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  132. package/templates/podcast-creator/dev/index.ts +1 -0
  133. package/templates/podcast-creator/tier5-src/_shared/member-bookings.ts +17 -4
  134. package/templates/podcast-creator-owner/dev/index.ts +54 -0
  135. package/templates/podcast-creator-owner/tier5-src/_shared/aria-chat.ts +30 -4
  136. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  137. package/templates/portfolio-creative/dev/index.ts +1 -0
  138. package/templates/portfolio-creative/tier5-src/_shared/member-bookings.ts +17 -4
  139. package/templates/portfolio-creative-owner/dev/index.ts +54 -0
  140. package/templates/portfolio-creative-owner/tier5-src/_shared/aria-chat.ts +30 -4
  141. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  142. package/templates/restaurant/dev/index.ts +1 -0
  143. package/templates/restaurant/tier5-src/_shared/member-bookings.ts +17 -4
  144. package/templates/restaurant-owner/dev/index.ts +54 -0
  145. package/templates/restaurant-owner/tier5-src/_shared/aria-chat.ts +30 -4
  146. package/templates/restaurant-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  147. package/templates/retail-store/dev/index.ts +1 -0
  148. package/templates/retail-store/tier5-src/_shared/member-bookings.ts +17 -4
  149. package/templates/retail-store-owner/dev/index.ts +54 -0
  150. package/templates/retail-store-owner/tier5-src/_shared/aria-chat.ts +30 -4
  151. package/templates/retail-store-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
  152. package/templates/salon-spa/dev/index.ts +1 -0
  153. package/templates/salon-spa/tier5-src/_shared/member-bookings.ts +17 -4
  154. package/templates/salon-spa/tier5-src/_shared/staff-name.ts +18 -0
  155. package/templates/salon-spa/tier5-src/himi-booking-bookings/index.ts +6 -2
  156. package/templates/salon-spa/tier5-src/himi-booking-service/index.ts +7 -2
  157. package/templates/salon-spa/tier5-src/himi-booking-time/index.ts +6 -4
  158. package/templates/wholesale-store/dev/index.ts +1 -0
  159. package/templates/yoga-studio/dev/index.ts +1 -0
  160. package/templates/yoga-studio/l10n/en.json +6 -0
  161. package/templates/yoga-studio/l10n/fr.json +11 -0
  162. package/templates/yoga-studio/l10n/he.json +9 -0
  163. package/templates/yoga-studio/tier5-src/_shared/member-bookings.ts +17 -4
  164. package/templates/yoga-studio/tier5-src/_shared/staff-name.ts +18 -0
  165. package/templates/yoga-studio/tier5-src/himi-booking-bookings/index.ts +6 -2
  166. package/templates/yoga-studio/tier5-src/himi-booking-service/index.ts +7 -2
  167. package/templates/yoga-studio/tier5-src/himi-booking-time/index.ts +6 -4
  168. package/templates/yoga-studio-owner/dev/index.ts +54 -0
  169. package/templates/yoga-studio-owner/tier5-src/_shared/aria-chat.ts +30 -4
  170. package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-aria/index.ts +29 -0
@@ -0,0 +1,106 @@
1
+ import { copyParam } from "./himi-copy.js";
2
+
3
+ export interface AttendanceField {
4
+ id: string;
5
+ label: string;
6
+ kind: string;
7
+ required: boolean;
8
+ value: string;
9
+ selectedIds: string[];
10
+ options: { id: string; label: string }[];
11
+ error: string;
12
+ maxLength?: number;
13
+ maxSize?: number;
14
+ }
15
+
16
+ const object = (v: unknown): Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record<string, unknown> : {};
17
+ const text = (v: unknown): string => typeof v === "string" ? v : "";
18
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
19
+
20
+ export function createAttendanceForm(prefix: string) {
21
+ let fields: AttendanceField[] = [];
22
+ let supported = false;
23
+ const label = (name: string) => copyParam(`${prefix}.${name}Label`, name === "firstName" ? "First name" : name === "lastName" ? "Last name" : "Email");
24
+ const field = (scope: string, name: string, input: Record<string, unknown> = {}): AttendanceField => ({
25
+ id: `${scope}:${name}`, label: text(input.label) || label(name), required: input.mandatory === true,
26
+ kind: name === "email" ? "email" : input.type === "NUMBER" ? "number" : input.type === "TEXT_ARRAY" ? "multiple" : Array.isArray(input.options) && input.options.length ? "choice" : "text",
27
+ value: "", selectedIds: [], error: "",
28
+ options: Array.isArray(input.options) ? input.options.filter((o): o is string => typeof o === "string").map((o) => ({ id: o, label: o })) : [],
29
+ ...(typeof input.maxLength === "number" ? { maxLength: input.maxLength } : {}),
30
+ ...(typeof input.maxSize === "number" ? { maxSize: input.maxSize } : {}),
31
+ });
32
+ const contact = (scope: string) => ["firstName", "lastName", "email"].map((name) => field(scope, name, { mandatory: true }));
33
+
34
+ function event(raw: unknown): void {
35
+ fields = contact("buyer");
36
+ const controls = object(raw).controls;
37
+ supported = Array.isArray(controls) && controls.length > 0;
38
+ const names = new Set<string>();
39
+ for (const control of Array.isArray(controls) ? controls : []) {
40
+ const c = object(control);
41
+ if (c.deleted === true) continue;
42
+ if (!Array.isArray(c.inputs) || !c.inputs.length) { supported = false; continue; }
43
+ for (const rawInput of c.inputs) {
44
+ const input = object(rawInput);
45
+ const name = text(input.name);
46
+ if (!name || names.has(name) || !["TEXT", "NUMBER", "TEXT_ARRAY"].includes(text(input.type)) || (input.type === "TEXT_ARRAY" && (!Array.isArray(input.options) || !input.options.length))) { supported = false; continue; }
47
+ names.add(name);
48
+ fields.push(field("guest", name, { ...input, mandatory: input.mandatory === true || ["firstName", "lastName", "email"].includes(name) }));
49
+ }
50
+ }
51
+ if (!["firstName", "lastName", "email"].every((name) => names.has(name))) supported = false;
52
+ }
53
+
54
+ function booking(service: unknown): void {
55
+ fields = contact("buyer");
56
+ const id = text(object(object(service).form).id);
57
+ // Custom intake schemas need their own reader; never silently omit their required fields.
58
+ supported = id === "00000000-0000-0000-0000-000000000000";
59
+ }
60
+
61
+ function change(arg: unknown): void {
62
+ const a = object(arg);
63
+ const f = fields.find((candidate) => candidate.id === a.id);
64
+ if (!f) return;
65
+ if (typeof a.option === "string") {
66
+ if (f.kind === "multiple") f.selectedIds = f.selectedIds.includes(a.option) ? f.selectedIds.filter((v) => v !== a.option) : [...f.selectedIds, a.option];
67
+ else f.value = a.option;
68
+ f.error = "";
69
+ return;
70
+ }
71
+ f.value = text(a.value ?? a.text ?? a.selectedId);
72
+ f.selectedIds = Array.isArray(a.selectedIds) ? a.selectedIds.filter((v): v is string => typeof v === "string") : [];
73
+ f.error = "";
74
+ }
75
+
76
+ function valid(f: AttendanceField): boolean {
77
+ const value = f.value.trim();
78
+ const values = f.kind === "multiple" ? f.selectedIds : value ? [value] : [];
79
+ if (!values.length) return !f.required;
80
+ if (f.options.length && values.some((v) => !f.options.some((o) => o.id === v))) return false;
81
+ if (f.maxSize !== undefined && values.length > f.maxSize) return false;
82
+ if (f.maxLength !== undefined && values.some((v) => v.length > f.maxLength!)) return false;
83
+ return f.kind === "email" ? EMAIL.test(value) : f.kind !== "number" || /^-?\d+(?:\.\d+)?$/.test(value);
84
+ }
85
+
86
+ function validate(): boolean {
87
+ for (const f of fields) f.error = valid(f) ? "" : copyParam(`${prefix}.formInvalidText`, "Check this field.");
88
+ return supported && fields.every((f) => !f.error);
89
+ }
90
+
91
+ function buyer(): Record<string, string> {
92
+ return Object.fromEntries(fields.filter((f) => f.id.startsWith("buyer:")).map((f) => [f.id.slice(6), f.value.trim()]));
93
+ }
94
+
95
+ function ticket(definitionId: string) {
96
+ const inputValues = fields.filter((f) => f.id.startsWith("guest:") && (f.value.trim() || f.selectedIds.length)).map((f) => ({ inputName: f.id.slice(6), ...(f.kind === "multiple" ? { values: f.selectedIds.slice() } : { value: f.value.trim() }) }));
97
+ return { buyer: buyer(), guests: [{ ticketDefinitionId: definitionId, form: { inputValues } }] };
98
+ }
99
+
100
+ return {
101
+ event, booking, change, validate, buyer, ticket,
102
+ supported: () => supported,
103
+ rows: () => fields.map((f) => ({ ...f, selectedIds: f.selectedIds.slice(), kind: f.kind === "text" && f.required ? "requiredText" : f.kind })),
104
+ clear: () => { for (const f of fields) { f.value = ""; f.selectedIds = []; f.error = ""; } },
105
+ };
106
+ }
@@ -0,0 +1,216 @@
1
+ import { attendanceCheckoutRoute, availableTicketAttendanceOf, bookingAttendanceOf, classifyForApple, hostSessionFromGlobal, iapPriceFields, type BookingAttendance, type CatalogReference, type IapPollDirective, type TicketAttendance } from "@himalaya/iap";
2
+ import { bookingOrders, createIapCommerce, eventTicketOrders, type IapOrderItem } from "@himalaya/iap-checkout";
3
+ import { copyParam, copyTemplate } from "./himi-copy.js";
4
+ import { createAttendanceForm, type AttendanceField } from "./iap-attendance-form.js";
5
+ import { attendancePlatform } from "./iap-attendance.js";
6
+ import { iapPriceCopy, iapPurchaseCopy } from "./iap-worker.js";
7
+
8
+ export interface AttendancePurchaseFields {
9
+ iapBuyHidden: boolean;
10
+ iapBuyDisabled: boolean;
11
+ iapBuyLabel: string;
12
+ iapBusy: boolean;
13
+ iapPrice: string;
14
+ iapNote: string;
15
+ iapRetryHidden: boolean;
16
+ iapFormHidden: boolean;
17
+ iapFormError: string;
18
+ iapSignInHidden: boolean;
19
+ iapFields: AttendanceField[];
20
+ _poll?: IapPollDirective;
21
+ }
22
+
23
+ export const ATTENDANCE_INITIAL: AttendancePurchaseFields = {
24
+ iapBuyHidden: true, iapBuyDisabled: true, iapBuyLabel: "", iapBusy: false,
25
+ iapPrice: "", iapNote: "", iapRetryHidden: true, iapFormHidden: true, iapFormError: "", iapSignInHidden: true, iapFields: [],
26
+ };
27
+ export const ATTENDANCE_NOT_HYDRATED = [...Object.keys(ATTENDANCE_INITIAL), "_poll"] as (keyof AttendancePurchaseFields & string)[];
28
+
29
+ const CORRECTABLE = new Set(["orderRefused", "productChanged", "memberDetailsRequired", "bookingNotOwned"]);
30
+
31
+ export function createAttendancePurchase(options: { kind: "bookingsService" | "eventsTicket"; prefix: string; pollAction: string; onChange(): void }) {
32
+ const { prefix } = options;
33
+ let form = createAttendanceForm(prefix);
34
+ const submittedForms = new Map<string, ReturnType<typeof createAttendanceForm>>();
35
+ const session = hostSessionFromGlobal();
36
+ const commerce = createIapCommerce({ adapters: [options.kind === "bookingsService" ? bookingOrders : eventTicketOrders], onChange: options.onChange });
37
+ let generation = session.current().generation;
38
+ let reference: CatalogReference | undefined;
39
+ let metadata: BookingAttendance | TicketAttendance | undefined;
40
+ let platform = "unknown";
41
+ let started = false;
42
+ let inFlight = false;
43
+ let formError = "";
44
+ let sequence = 0;
45
+ let formRevision = 0;
46
+ const attempts = new Map<string, string>();
47
+ session.subscribe(() => { syncSession(); if (reference) options.onChange(); });
48
+
49
+ function syncSession(): void {
50
+ const next = session.current().generation;
51
+ if (next === generation) return;
52
+ generation = next;
53
+ form.clear();
54
+ submittedForms.clear();
55
+ formError = "";
56
+ attempts.clear();
57
+ }
58
+
59
+ async function refresh(): Promise<void> {
60
+ const next = await attendancePlatform(publishPlatform);
61
+ if (next !== "unknown" || platform === "unknown") platform = next;
62
+ await resume();
63
+ }
64
+
65
+ async function resume(): Promise<void> {
66
+ if (reference) await commerce.loadPrices([{ reference }]);
67
+ const first = !started;
68
+ started = true;
69
+ await (first ? commerce.start() : commerce.reconcile());
70
+ }
71
+
72
+ function publishPlatform(next: string): void {
73
+ if (next === "unknown" && platform !== "unknown") return;
74
+ platform = next;
75
+ void resume().then(options.onChange, options.onChange);
76
+ }
77
+
78
+ function show(): void {
79
+ void attendancePlatform(publishPlatform).then(publishPlatform, options.onChange);
80
+ }
81
+
82
+ async function booking(id: string, service: unknown): Promise<void> {
83
+ syncSession();
84
+ reference = { kind: options.kind, id };
85
+ metadata = bookingAttendanceOf(service);
86
+ selectForm(id, (next) => next.booking(service));
87
+ formRevision++;
88
+ formError = "";
89
+ await show();
90
+ }
91
+
92
+ async function ticket(id: string, event: unknown, available: unknown): Promise<void> {
93
+ syncSession();
94
+ reference = id ? { kind: options.kind, id } : undefined;
95
+ metadata = availableTicketAttendanceOf(event, available);
96
+ selectForm(id, (next) => next.event((event as { form?: unknown } | undefined)?.form));
97
+ formRevision++;
98
+ formError = "";
99
+ await show();
100
+ }
101
+
102
+ function selectForm(id: string, initialize: (next: ReturnType<typeof createAttendanceForm>) => void): void {
103
+ const key = `${options.kind}:${id}`;
104
+ const retained = submittedForms.get(key);
105
+ form = retained ?? createAttendanceForm(prefix);
106
+ if (!retained) initialize(form);
107
+ }
108
+
109
+ function fields(selected = true, publishPoll = true): AttendancePurchaseFields {
110
+ syncSession();
111
+ if (!reference || !metadata) return ATTENDANCE_INITIAL;
112
+ const currency = metadata.currency ?? "";
113
+ const classified = classifyForApple(metadata, currency);
114
+ const candidate = platform === "ios" && classified === "appleIap";
115
+ const price = iapPriceFields(commerce.pricing.view(reference), iapPriceCopy(prefix));
116
+ const copy = iapPurchaseCopy(prefix);
117
+ const purchase = commerce.purchaseFields(reference, copy);
118
+ const apple = candidate || (platform === "ios" && classified !== "wixPayments" && purchase.appleRoute);
119
+ const enabled = attendanceCheckoutRoute(metadata, currency, platform) === "appleIap";
120
+ const poll = publishPoll ? commerce.pollDirective(options.pollAction) : undefined;
121
+ const state = commerce.state();
122
+ for (const [target, attempt] of attempts) {
123
+ const key = `${reference.kind}:${reference.id}#${encodeURIComponent(attempt)}`;
124
+ if ((state.phase === "accessReady" && state.item === key) || state.payments.some((p) => p.item === key && p.access === "granted")) attempts.delete(target);
125
+ }
126
+ const formKey = `${reference.kind}:${reference.id}`;
127
+ if (![...attempts.keys()].some((target) => target.startsWith(`${formKey}:`))) submittedForms.delete(formKey);
128
+ const own = state.item?.startsWith(`${reference.kind}:${reference.id}#`);
129
+ const completed = state.phase === "accessReady" && own;
130
+ const member = session.current().kind === "member";
131
+ let note = "";
132
+ if (apple && !enabled) note = copy.unavailable;
133
+ else if (apple && !member) note = copy.signInRequired;
134
+ else if (apple && purchase.buyNote) note = purchase.buyNote;
135
+ else if (apple && !form.supported()) note = copyParam(`${prefix}.formUnavailableText`, "This registration form is not supported yet.");
136
+ else if (apple && completed) note = copyParam(`${prefix}.purchaseCompleteText`, options.kind === "bookingsService" ? "Your booking is confirmed." : "Your ticket is confirmed.");
137
+ else if (apple && own && state.phase === "cancelled") note = copyParam(`${prefix}.purchaseCancelledText`, "Purchase cancelled. Your place is not confirmed.");
138
+ return {
139
+ iapBuyHidden: !apple, iapBuyDisabled: !enabled || !selected || !member || !form.supported() || purchase.buyDisabled || inFlight,
140
+ iapBuyLabel: purchase.buyLabel || copy.buy, iapBusy: purchase.buyBusy || inFlight,
141
+ iapPrice: apple ? price.priceText : "", iapRetryHidden: !apple || (price.hidePriceRetry && commerce.scopeComplete()),
142
+ iapNote: note,
143
+ iapFormHidden: !apple || !selected || !form.supported(), iapFormError: formError,
144
+ iapSignInHidden: !apple || member || options.kind === "bookingsService",
145
+ iapFields: form.rows().map((f, index, rows) => ({ ...f,
146
+ id: `${generation}:${formRevision}:${f.id}`, fieldId: f.id,
147
+ errorHidden: !f.error,
148
+ options: f.options.map((o) => ({ ...o, fieldId: f.id, displayLabel: (f.kind === "multiple" ? f.selectedIds.includes(o.id) : f.value === o.id) ? `${o.label} ✓` : o.label })),
149
+ label: f.required ? `${f.label} *` : f.label,
150
+ inputLabel: copyTemplate(`${prefix}.fieldAccessibilityLabel`, "{section}: {field}", { section: f.id.startsWith("buyer:") ? copyParam(`${prefix}.buyerDetailsLabel`, "Buyer details") : copyParam(`${prefix}.guestDetailsLabel`, "Ticket holder details"), field: f.label }),
151
+ sectionLabel: index === 0 ? copyParam(`${prefix}.buyerDetailsLabel`, "Buyer details") : f.id.startsWith("guest:") && rows[index - 1].id.startsWith("buyer:") ? copyParam(`${prefix}.guestDetailsLabel`, "Ticket holder details") : "",
152
+ })), ...(poll ? { _poll: poll } : {}),
153
+ };
154
+ }
155
+
156
+ async function buy(selection: { key: string; slot?: Record<string, unknown>; eventId?: string }): Promise<void> {
157
+ syncSession();
158
+ if (!reference || !metadata || fields(true, false).iapBuyDisabled || inFlight) return;
159
+ if (options.kind === "eventsTicket" && reference.id !== selection.key) return;
160
+ if (!form.validate()) { formError = copyParam(`${prefix}.formRequiredText`, "Complete the required details before purchasing."); return; }
161
+ if (session.current().kind !== "member") { formError = iapPurchaseCopy(prefix).signInRequired; return; }
162
+ const currentGeneration = generation;
163
+ const ref = reference;
164
+ submittedForms.set(`${ref.kind}:${ref.id}`, form);
165
+ const target = `${ref.kind}:${ref.id}:${selection.key}`;
166
+ let attemptId = attempts.get(target);
167
+ const state = commerce.state();
168
+ const attemptKey = attemptId ? `${ref.kind}:${ref.id}#${encodeURIComponent(attemptId)}` : "";
169
+ const completed = attemptId && ((state.phase === "accessReady" && state.item === attemptKey) || state.payments.some((p) => p.item === attemptKey && p.access === "granted"));
170
+ if (!attemptId || completed) { attemptId = `${Date.now().toString(36)}-${++sequence}-${Math.random().toString(36).slice(2)}`; attempts.set(target, attemptId); }
171
+ const item: IapOrderItem = { reference: ref, attemptId, quantity: 1, attendance: {
172
+ amount: metadata.amount!, currency: metadata.currency!,
173
+ ...(options.kind === "bookingsService" ? { booking: { slot: selection.slot ?? {}, contactDetails: form.buyer() } } : { ticket: { eventId: selection.eventId ?? "", ...form.ticket(ref.id) } }),
174
+ } };
175
+ inFlight = true;
176
+ formError = "";
177
+ options.onChange();
178
+ try {
179
+ await commerce.buy(item);
180
+ const after = commerce.state();
181
+ if (after.phase === "accessReady" && after.item === `${ref.kind}:${ref.id}#${encodeURIComponent(attemptId)}`) attempts.delete(target);
182
+ }
183
+ finally { inFlight = false; syncSession(); if (generation !== currentGeneration) form.clear(); options.onChange(); }
184
+ }
185
+
186
+ function change(arg: unknown): void {
187
+ syncSession();
188
+ const state = commerce.state();
189
+ if (reference) {
190
+ for (const [target, attempt] of attempts) {
191
+ const item = `${reference.kind}:${reference.id}#${encodeURIComponent(attempt)}`;
192
+ // Refusals that leave nothing to pay: the member may fix the details (a profile, a booking the
193
+ // server did not attribute to them) and start a fresh attempt. A transient failure keeps the
194
+ // attempt, so its next tap reopens the same order instead of booking twice.
195
+ const canCorrect = state.phase === "cancelled" || (state.phase === "refused" && CORRECTABLE.has(state.failure ?? ""));
196
+ if (canCorrect && state.item === item) { attempts.delete(target); submittedForms.delete(`${reference.kind}:${reference.id}`); }
197
+ }
198
+ const referencePrefix = `${reference.kind}:${reference.id}:`;
199
+ if (inFlight || [...attempts.keys()].some((target) => target.startsWith(referencePrefix))) {
200
+ formError = copyParam(`${prefix}.detailsLockedText`, "Finish the current purchase before changing registration details.");
201
+ return;
202
+ }
203
+ }
204
+ form.change(arg);
205
+ formError = "";
206
+ }
207
+
208
+ return {
209
+ booking, ticket, fields, buy,
210
+ usesRegularPlatform: () => platform === "android" || platform === "web",
211
+ invalidate: () => { reference = undefined; metadata = undefined; options.onChange(); },
212
+ change,
213
+ refresh,
214
+ poll: async () => { syncSession(); await commerce.poll(); },
215
+ };
216
+ }
@@ -0,0 +1,38 @@
1
+ import { get as appInfo } from "@himalaya/app-info";
2
+ import { attendanceCheckoutRoute, bookingAttendanceOf, ticketAttendanceOf } from "@himalaya/iap";
3
+
4
+ let knownPlatform: string | undefined;
5
+
6
+ export function attendancePlatform(onResolved?: (platform: string) => void): Promise<string> {
7
+ if (knownPlatform) return Promise.resolve(knownPlatform);
8
+ const info = appInfo().then((value) => value.platform, () => "unknown").then((platform) => {
9
+ if (platform !== "unknown") knownPlatform = platform;
10
+ return platform;
11
+ });
12
+ const host = globalThis as { setTimeout?: (fn: () => void, ms: number) => unknown; clearTimeout?: (timer: unknown) => void };
13
+ if (!host.setTimeout) {
14
+ void info.then((platform) => onResolved?.(platform));
15
+ return Promise.resolve("unknown");
16
+ }
17
+ return new Promise((resolve) => {
18
+ let timedOut = false;
19
+ const timer = host.setTimeout!(() => { timedOut = true; resolve("unknown"); }, 1500);
20
+ void info.then((platform) => { host.clearTimeout?.(timer); resolve(platform); if (timedOut) onResolved?.(platform); });
21
+ });
22
+ }
23
+
24
+ export async function mayUseRegularBookingCheckout(service: unknown): Promise<boolean> {
25
+ const metadata = bookingAttendanceOf(service);
26
+ if (metadata.priceType === "NO_FEE" || isZero(metadata.amount)) return true;
27
+ return attendanceCheckoutRoute(metadata, metadata.currency ?? "", await attendancePlatform()) === "regular";
28
+ }
29
+
30
+ export async function mayUseRegularTicketCheckout(event: unknown, ticket: { free?: boolean; price?: { amount?: string; currency?: string }; saleStatus?: string } | undefined): Promise<boolean> {
31
+ if (ticket?.free === true || isZero(ticket?.price?.amount)) return true;
32
+ const metadata = ticketAttendanceOf(event, { hidden: false, saleStatus: ticket?.saleStatus });
33
+ return attendanceCheckoutRoute(metadata, ticket?.price?.currency ?? "", await attendancePlatform()) === "regular";
34
+ }
35
+
36
+ function isZero(value: unknown): boolean {
37
+ return typeof value === "string" && /^0+(?:\.0+)?$/.test(value);
38
+ }
@@ -0,0 +1,127 @@
1
+ // Worker-side glue for the shared IAP layer (`@himalaya/iap` catalog pricing and
2
+ // `@himalaya/iap-checkout` → createIapCommerce), shared by every screen that shows or sells an
3
+ // IAP-backed item. Mapping, Apple prices, payment guards, the host scope and the sale live in the
4
+ // SDK; this only supplies the copy and the hydration reset.
5
+ import { hostSessionFromGlobal, type IapPriceCopy } from "@himalaya/iap";
6
+ import type { IapCommerce, IapPurchaseCopy, IapRestoreResult } from "@himalaya/iap-checkout";
7
+ import { paymentSetupMessage } from "./payment-setup.js";
8
+ import { copyParam, copyTemplate } from "./himi-copy.js";
9
+
10
+ /** Price labels from the screen's copy pack (`<prefix>.priceLoadingText`, …). */
11
+ export function iapPriceCopy(prefix: string): IapPriceCopy {
12
+ return {
13
+ loading: copyParam(`${prefix}.priceLoadingText`, "Loading price…"),
14
+ unavailable: copyParam(`${prefix}.priceUnavailableText`, "Price unavailable"),
15
+ oneTimePurchase: copyParam(`${prefix}.oneTimePurchaseLabel`, "One-time purchase"),
16
+ purchaseUnavailable: copyParam(`${prefix}.purchaseUnavailableText`, "Purchasing is not available yet."),
17
+ };
18
+ }
19
+
20
+ /** App Store purchase labels from the screen's copy pack (`<prefix>.buyCta`, …), for
21
+ * `iapPurchaseFields`. Customer copy only: no backend names, ids or diagnostics. */
22
+ export function iapPurchaseCopy(prefix: string): IapPurchaseCopy {
23
+ return {
24
+ buy: copyParam(`${prefix}.buyCta`, "Buy now"),
25
+ processing: copyParam(`${prefix}.purchaseProcessingText`, "Processing your purchase…"),
26
+ awaitingApproval: copyParam(`${prefix}.purchaseAwaitingApprovalText`, "Waiting for approval"),
27
+ unavailable: copyParam(`${prefix}.purchaseTemporarilyUnavailableText`, "Purchasing is temporarily unavailable."),
28
+ signInRequired: copyParam(`${prefix}.purchaseSignInText`, "Sign in to buy."),
29
+ sitePaymentUnavailable: paymentSetupMessage(prefix),
30
+ memberDetailsRequired: copyParam(`${prefix}.purchaseMemberDetailsText`, "Add your first name, last name and email to your profile, then try again."),
31
+ alreadySubscribed: copyParam(`${prefix}.purchaseAlreadySubscribedText`, "You already have a subscription in this app."),
32
+ retry: copyParam(`${prefix}.purchaseRetryText`, "Something went wrong. Try again."),
33
+ priceChanged: copyParam(`${prefix}.purchasePriceChangedText`, "The price changed. Check it and try again."),
34
+ support: copyParam(`${prefix}.purchaseSupportText`, "We couldn't finish this purchase. Contact support."),
35
+ };
36
+ }
37
+
38
+ /** The Restore purchases control (App Review 3.1.1) a screen binds. */
39
+ export interface IapRestoreFields {
40
+ restoreHidden: boolean;
41
+ restoreLabel: string;
42
+ restoreDisabled: boolean;
43
+ restoreMessage: string;
44
+ }
45
+
46
+ /** Keep these out of hydration: a restore's answer belongs to the run that got it. */
47
+ export const IAP_RESTORE_KEYS = ["restoreHidden", "restoreLabel", "restoreDisabled", "restoreMessage"] as const;
48
+
49
+ /** The control before the screen knows it sells through Apple. */
50
+ export const NO_IAP_RESTORE: IapRestoreFields = { restoreHidden: true, restoreLabel: "", restoreDisabled: false, restoreMessage: "" };
51
+
52
+ export interface IapRestoreControl {
53
+ /** `sellsThroughApple` is the screen's own signal: its item's App Store route, or Account's
54
+ * purchase readiness. */
55
+ fields(sellsThroughApple: boolean): IapRestoreFields;
56
+ /** Runs the shared `commerce.restore()`, repainting as it starts and when it answers. A tap while
57
+ * one runs is ignored. */
58
+ run(): Promise<void>;
59
+ }
60
+
61
+ /** Copy from the screen's pack (`<prefix>.restorePurchasesCta`, …). The restore itself, and the access
62
+ * re-read after it, are the shared commerce's. */
63
+ export function createIapRestore(
64
+ commerce: Pick<IapCommerce, "restore">,
65
+ options: { prefix: string; repaint(): void; /** The session generation; defaults to the host's. */ generation?: () => number },
66
+ ): IapRestoreControl {
67
+ const generation = options.generation ?? (() => hostSessionFromGlobal().current().generation);
68
+ let running = false;
69
+ let message = "";
70
+ let messageGeneration = -1;
71
+
72
+ function say(text: string, forGeneration: number): void {
73
+ message = text;
74
+ messageGeneration = forGeneration;
75
+ }
76
+
77
+ async function run(): Promise<void> {
78
+ if (running) return;
79
+ running = true;
80
+ const startedFor = generation();
81
+ say(copyParam(`${options.prefix}.restoringText`, "Restoring…"), startedFor);
82
+ options.repaint();
83
+ // Stamped with the session the tap was for: an answer landing after a sign-out is never shown.
84
+ say(restoreMessage(await restored(commerce), options.prefix), startedFor);
85
+ running = false;
86
+ options.repaint();
87
+ }
88
+
89
+ return {
90
+ fields: (sellsThroughApple) => ({
91
+ restoreHidden: !sellsThroughApple,
92
+ restoreLabel: copyParam(`${options.prefix}.restorePurchasesCta`, "Restore purchases"),
93
+ restoreDisabled: running,
94
+ // The answer was for the person signed in when it ran; another session never inherits it.
95
+ restoreMessage: sellsThroughApple && messageGeneration === generation() ? message : "",
96
+ }),
97
+ run,
98
+ };
99
+ }
100
+
101
+ function restored(commerce: Pick<IapCommerce, "restore">): Promise<IapRestoreResult> {
102
+ return commerce.restore().catch(() => ({ status: "failed", code: "storeUnavailable" }) as const);
103
+ }
104
+
105
+ function restoreMessage(result: IapRestoreResult, prefix: string): string {
106
+ if (result.status === "needsSignIn") return copyParam(`${prefix}.restoreSignInText`, "Sign in to restore your purchases.");
107
+ if (result.status === "failed") return result.code === "sessionChanged" ? "" : copyParam(`${prefix}.restoreFailedText`, "Couldn't reach the App Store. Try again.");
108
+ // Every part that happened is said: a recovery never hides a refusal or a purchase still pending.
109
+ const parts = [
110
+ result.recovered === 1 ? copyParam(`${prefix}.restoredOneText`, "Restored 1 purchase.") : "",
111
+ result.recovered > 1 ? copyTemplate(`${prefix}.restoredManyText`, "Restored {count} purchases.", { count: result.recovered }) : "",
112
+ // Held unfinished because Wix refused it (another member's purchase, say).
113
+ result.refused > 0 ? copyParam(`${prefix}.restoreRefusedText`, "A purchase on this Apple ID couldn't be added to this account. Contact support.") : "",
114
+ result.pending > 0 ? copyParam(`${prefix}.restorePendingText`, "A purchase is still being confirmed. Try again in a moment.") : "",
115
+ ].filter(Boolean);
116
+ return parts.length ? parts.join(" ") : copyParam(`${prefix}.restoreUpToDateText`, "Your purchases are up to date.");
117
+ }
118
+
119
+ /** What `notHydrated` does, for a runtime that ignores the option (a binary older than it, still
120
+ * served new bundles): put the listed keys back to their declared values before any action runs,
121
+ * so a persisted price or an enabled purchase action never paints as this run's. */
122
+ export function resetUnhydratedKeysOnOlderRuntime<S extends object>(svc: { getState(): S }, declared: S, keys: readonly (keyof S & string)[]): void {
123
+ if ((globalThis as { himalaya?: { hydrationOptOut?: unknown } }).himalaya?.hydrationOptOut === true) return;
124
+ const booted = svc.getState();
125
+ if (!booted || typeof booted !== "object") return;
126
+ for (const key of keys) booted[key] = declared[key];
127
+ }
@@ -0,0 +1,68 @@
1
+ // The member's Inbox rows: every chatroom the member-role chat list returns, business and member alike.
2
+ // Pure, so the worker and its tests share one classification of what a room is.
3
+
4
+ type RecordValue = Record<string, unknown>;
5
+ const object = (value: unknown): RecordValue =>
6
+ value !== null && typeof value === "object" && !Array.isArray(value) ? value as RecordValue : {};
7
+
8
+ /** The two-party room between the member and the business (the Smart Chat room). Another member's
9
+ * room has no `businessContext`, and a contact-less room is not the business's. */
10
+ export function isBusinessRoom(value: unknown): boolean {
11
+ const room = object(value);
12
+ return typeof room.id === "string" && !!room.id &&
13
+ typeof room.participantId === "string" && !!room.participantId &&
14
+ room.participantCount === 2 && room.clientReferenceType === "contactId" &&
15
+ Object.keys(object(room.businessContext)).length > 0;
16
+ }
17
+
18
+ export interface InboxRow {
19
+ id: string;
20
+ title: string;
21
+ subtitle: string;
22
+ /** The screen a tap opens: the business chat for the business room, a thread for any other. */
23
+ screenId: "himi_business_chat" | "himi_chat_thread";
24
+ /** `chatroom` makes the thread use `id` as the room instead of resolving it as a member id. */
25
+ kind: "chatroom" | "";
26
+ photo: string;
27
+ initial: string;
28
+ unread: boolean;
29
+ unreadDot: string;
30
+ /** Sort key only; not bound to the screen. */
31
+ at: number;
32
+ }
33
+
34
+ const text = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
35
+
36
+ function titleOf(room: RecordValue, business: boolean): string {
37
+ const display = text(object(room.displayData).name);
38
+ if (business) return text(object(room.businessContext).name) || display;
39
+ return display;
40
+ }
41
+
42
+ /** Newest conversation first; archived rooms and rooms without an id are dropped. `fallbackTitle` names a
43
+ * room that carries no name (the caller passes the localised word, not a hard-coded English one). */
44
+ export function inboxRows(rooms: unknown[], fallbackTitle: string): InboxRow[] {
45
+ const rows: InboxRow[] = [];
46
+ for (const value of rooms) {
47
+ const room = object(value);
48
+ const id = text(room.id);
49
+ if (!id || room.isArchived === true) continue;
50
+ const business = isBusinessRoom(room);
51
+ const title = titleOf(room, business) || fallbackTitle;
52
+ const last = object(room.lastMessage);
53
+ const unread = typeof room.unreadCount === "number" && room.unreadCount > 0;
54
+ rows.push({
55
+ id,
56
+ title,
57
+ subtitle: text(last.summary),
58
+ screenId: business ? "himi_business_chat" : "himi_chat_thread",
59
+ kind: business ? "" : "chatroom",
60
+ photo: text(object(object(room.displayData).image).url),
61
+ initial: (title[0] ?? "#").toUpperCase(),
62
+ unread,
63
+ unreadDot: unread ? "●" : "",
64
+ at: typeof last.createdAt === "number" ? last.createdAt : typeof room.createdAt === "number" ? room.createdAt : 0,
65
+ });
66
+ }
67
+ return rows.sort((a, b) => b.at - a.at);
68
+ }
@@ -0,0 +1,38 @@
1
+ /** Small local preferences only; never entity records or credentials. The host
2
+ * overwrites these reserved input fields from its authenticated account/site.
3
+ * Older hosts and visitors deliberately stay session-only. */
4
+ export interface PreferenceStore {
5
+ getItem(key: string): string | null;
6
+ setItem(key: string, value: string): void;
7
+ }
8
+ export interface PreferenceRuntime { input?: Record<string, unknown>; storage?: PreferenceStore; }
9
+ export function localPreferences<T>(name: string, normalize: (value: unknown) => T, runtime?: PreferenceRuntime) {
10
+ const host = runtime ?? (globalThis as { himalaya?: PreferenceRuntime }).himalaya;
11
+ const account = host?.input?.__himiPreferenceAccount;
12
+ const business = host?.input?.__himiPreferenceBusiness;
13
+ const valid = (value: unknown): value is string => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,128}$/.test(value) && value !== 'default';
14
+ const key = valid(account) && valid(business) && host?.storage
15
+ ? `himi.preferences.v1.${account}.${encodeURIComponent(business)}.${name}` : '';
16
+ let available = !!key;
17
+ return {
18
+ get available() { return available; },
19
+ read(): T {
20
+ if (!key) return normalize(undefined);
21
+ try {
22
+ const raw = host!.storage!.getItem(key);
23
+ if (!raw || raw.length > 32768) return normalize(undefined);
24
+ const data = JSON.parse(raw);
25
+ return normalize(data?.version === 1 ? data.value : undefined);
26
+ } catch { available = false; return normalize(undefined); }
27
+ },
28
+ write(value: T): void {
29
+ if (!key) return;
30
+ try {
31
+ const raw = JSON.stringify({ version: 1, value: normalize(value) });
32
+ if (raw.length > 32768) { available = false; return; }
33
+ host!.storage!.setItem(key, raw);
34
+ available = host!.storage!.getItem(key) === raw;
35
+ } catch { available = false; }
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,52 @@
1
+ import { dispatch } from "@himalaya/dispatch";
2
+ import { getMyData } from "@himalaya/wix-users";
3
+
4
+ export interface MemberAccess { email: string; scope: string; }
5
+ export function memberAccessChanged(): Error {
6
+ const error = new Error("Member access changed"); error.name = "MemberAccessChanged"; return error;
7
+ }
8
+ export async function memberAccess(): Promise<MemberAccess> {
9
+ let email = "";
10
+ let identityUnavailable = false;
11
+ try {
12
+ const value = await dispatch("himi.wix.memberIdentity") as { email?: unknown; payload?: { email?: unknown } } | null;
13
+ const raw = value?.email ?? value?.payload?.email;
14
+ email = typeof raw === "string" ? raw.trim().toLowerCase() : "";
15
+ } catch { identityUnavailable = true; }
16
+ // Older native hosts predate the memberIdentity action but can still expose
17
+ // the authenticated profile through wix-users. Only a missing action uses
18
+ // that rung: an explicit empty current-session response remains a visitor.
19
+ if (!email && identityUnavailable) {
20
+ try {
21
+ const profile = await getMyData();
22
+ const raw = profile.email ?? profile.contactEmail;
23
+ email = typeof raw === "string" ? raw.trim().toLowerCase() : "";
24
+ } catch { /* A visitor or an unavailable legacy profile remains anonymous. */ }
25
+ }
26
+ const input = (globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input;
27
+ const account = input?.__himiPreferenceAccount, business = input?.__himiPreferenceBusiness;
28
+ const valid = (v: unknown): v is string => typeof v === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(v) && v !== "default";
29
+ // These fields are overwritten by authenticated hosts. Older binaries stay online-only.
30
+ return { email, scope: email && valid(account) && valid(business) ? JSON.stringify([account, business, email]) : "" };
31
+ }
32
+ export async function assertMemberAccess(member: MemberAccess): Promise<void> {
33
+ const current = await memberAccess();
34
+ if (!member.email || current.email !== member.email || current.scope !== member.scope) throw memberAccessChanged();
35
+ }
36
+ export function memberAccessDenied(error: unknown): boolean {
37
+ return (error as { name?: string } | null)?.name === "MemberAccessChanged" || /(?:HTTP\s*(?:401|403)|READ_ORDER_FORBIDDEN|permission denied|forbidden)/i.test(String(error));
38
+ }
39
+
40
+ /** Did this write fail because the member changed (signed out, or another account)? Then
41
+ * the screen reloads for whoever is signed in now. A 401/403 for the SAME member is only a
42
+ * failed write: the caller keeps what the member typed and says so. */
43
+ export async function memberChanged(member: MemberAccess | undefined, error: unknown): Promise<boolean> {
44
+ if ((error as { name?: string } | null)?.name === "MemberAccessChanged") return true;
45
+ if (!member || !memberAccessDenied(error)) return false;
46
+ try {
47
+ await assertMemberAccess(member);
48
+ return false;
49
+ } catch {
50
+ return true;
51
+ }
52
+ }