@wix/himalaya-cli 0.1641.0 → 0.1643.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 (89) hide show
  1. package/dist/cli.mjs +327 -155
  2. package/guides/himi-json-output.md +20 -1
  3. package/guides/qa-builds.md +33 -0
  4. package/package.json +2 -2
  5. package/template-icons/conference.png +0 -0
  6. package/templates/branded-lite/dev/index.ts +152 -88
  7. package/templates/branded-lite/l10n/en.json +1 -1
  8. package/templates/branded-lite/tier5-src/_shared/featured-event.ts +63 -0
  9. package/templates/branded-lite/tier5-src/himi-events-detail/index.ts +93 -11
  10. package/templates/community-club/dev/index.ts +152 -88
  11. package/templates/community-club/tier5-src/_shared/featured-event.ts +63 -0
  12. package/templates/community-club/tier5-src/himi-events-detail/index.ts +93 -11
  13. package/templates/conference/README.md +53 -0
  14. package/templates/conference/config.ts +321 -0
  15. package/templates/conference/dev/index.ts +17252 -0
  16. package/templates/conference/himalaya.content.json +46 -0
  17. package/templates/conference/himalaya.template.json +15 -0
  18. package/templates/conference/icon.png +0 -0
  19. package/templates/conference/platforms.json +1 -0
  20. package/templates/conference/tier5-src/_shared/agenda-stars.ts +64 -0
  21. package/templates/conference/tier5-src/_shared/app-locale.ts +61 -0
  22. package/templates/conference/tier5-src/_shared/branded-lite-hosted.ts +279 -0
  23. package/templates/conference/tier5-src/_shared/branded-load-state.ts +109 -0
  24. package/templates/conference/tier5-src/_shared/business-chat-copy.ts +40 -0
  25. package/templates/conference/tier5-src/_shared/business-chat-history.ts +51 -0
  26. package/templates/conference/tier5-src/_shared/business-chat-message-model.ts +177 -0
  27. package/templates/conference/tier5-src/_shared/business-chat-model.ts +56 -0
  28. package/templates/conference/tier5-src/_shared/business-chat-presenter.ts +576 -0
  29. package/templates/conference/tier5-src/_shared/business-chat-transport.ts +148 -0
  30. package/templates/conference/tier5-src/_shared/collection-contract.ts +229 -0
  31. package/templates/conference/tier5-src/_shared/collection-query.ts +193 -0
  32. package/templates/conference/tier5-src/_shared/collection-service.ts +400 -0
  33. package/templates/conference/tier5-src/_shared/engine-intl.ts +508 -0
  34. package/templates/conference/tier5-src/_shared/event-agenda.ts +122 -0
  35. package/templates/conference/tier5-src/_shared/event-registration.ts +86 -0
  36. package/templates/conference/tier5-src/_shared/featured-event.ts +63 -0
  37. package/templates/conference/tier5-src/_shared/himi-account.ts +164 -0
  38. package/templates/conference/tier5-src/_shared/himi-copy.ts +89 -0
  39. package/templates/conference/tier5-src/_shared/himi-events.ts +65 -0
  40. package/templates/conference/tier5-src/_shared/himi-store.ts +7 -0
  41. package/templates/conference/tier5-src/_shared/hosted-checkout.ts +70 -0
  42. package/templates/conference/tier5-src/_shared/iap-attendance-form.ts +106 -0
  43. package/templates/conference/tier5-src/_shared/iap-attendance-purchase.ts +211 -0
  44. package/templates/conference/tier5-src/_shared/iap-attendance.ts +38 -0
  45. package/templates/conference/tier5-src/_shared/iap-worker.ts +125 -0
  46. package/templates/conference/tier5-src/_shared/inbox-rooms.ts +68 -0
  47. package/templates/conference/tier5-src/_shared/local-preferences.ts +38 -0
  48. package/templates/conference/tier5-src/_shared/member-access.ts +52 -0
  49. package/templates/conference/tier5-src/_shared/member-account-routes.ts +52 -0
  50. package/templates/conference/tier5-src/_shared/member-read.ts +52 -0
  51. package/templates/conference/tier5-src/_shared/member-screen.ts +99 -0
  52. package/templates/conference/tier5-src/_shared/offset-page.ts +10 -0
  53. package/templates/conference/tier5-src/_shared/online-actions.ts +76 -0
  54. package/templates/conference/tier5-src/_shared/owner-load-error.ts +348 -0
  55. package/templates/conference/tier5-src/_shared/payment-setup.ts +6 -0
  56. package/templates/conference/tier5-src/_shared/rich-body.ts +78 -0
  57. package/templates/conference/tier5-src/_shared/rich-content-link.ts +34 -0
  58. package/templates/conference/tier5-src/_shared/sign-in-sheet.ts +18 -0
  59. package/templates/conference/tier5-src/business-chat/index.ts +724 -0
  60. package/templates/conference/tier5-src/himi-conference-agenda/index.ts +183 -0
  61. package/templates/conference/tier5-src/himi-conference-home/index.ts +389 -0
  62. package/templates/conference/tier5-src/himi-events-account/index.ts +219 -0
  63. package/templates/conference/tier5-src/himi-events-detail/index.ts +1304 -0
  64. package/templates/conference/tier5-src/himi-events-list/index.ts +124 -0
  65. package/templates/conference/tier5-src/himi-events-my-events/index.ts +225 -0
  66. package/templates/conference/tier5-src/himi-events-rsvp/index.ts +230 -0
  67. package/templates/conference/tier5-src/himi-store-account/index.ts +998 -0
  68. package/templates/conference/tokens.json +365 -0
  69. package/templates/events-meetups/dev/index.ts +152 -88
  70. package/templates/events-meetups/tier5-src/_shared/featured-event.ts +63 -0
  71. package/templates/events-meetups/tier5-src/himi-events-detail/index.ts +93 -11
  72. package/templates/gym-fitness/dev/index.ts +152 -88
  73. package/templates/gym-fitness/tier5-src/_shared/featured-event.ts +63 -0
  74. package/templates/gym-fitness/tier5-src/himi-events-detail/index.ts +93 -11
  75. package/templates/nonprofit-cause/dev/index.ts +152 -88
  76. package/templates/nonprofit-cause/tier5-src/_shared/featured-event.ts +63 -0
  77. package/templates/nonprofit-cause/tier5-src/himi-events-detail/index.ts +93 -11
  78. package/templates/podcast-creator/dev/index.ts +152 -88
  79. package/templates/podcast-creator/tier5-src/_shared/featured-event.ts +63 -0
  80. package/templates/podcast-creator/tier5-src/himi-events-detail/index.ts +93 -11
  81. package/templates/portfolio-creative/dev/index.ts +152 -88
  82. package/templates/portfolio-creative/tier5-src/_shared/featured-event.ts +63 -0
  83. package/templates/portfolio-creative/tier5-src/himi-events-detail/index.ts +93 -11
  84. package/templates/restaurant/dev/index.ts +152 -88
  85. package/templates/restaurant/tier5-src/_shared/featured-event.ts +63 -0
  86. package/templates/restaurant/tier5-src/himi-events-detail/index.ts +93 -11
  87. package/templates/yoga-studio/dev/index.ts +152 -88
  88. package/templates/yoga-studio/tier5-src/_shared/featured-event.ts +63 -0
  89. package/templates/yoga-studio/tier5-src/himi-events-detail/index.ts +93 -11
@@ -0,0 +1,124 @@
1
+ // Tier-5 bundle: himi-events — public site events list.
2
+ import { defineBackendCollection } from "../_shared/collection-service.js";
3
+ import { queryEvents, type WixEvent } from "@himalaya/wix-events";
4
+ import { getAll, upsert, type DbEntity } from "@himalaya/local-db";
5
+ import { normalizeEvent, type EventRow } from "../_shared/himi-events";
6
+ import { offsetPage } from "../_shared/offset-page.js";
7
+ import { copyParam } from "../_shared/himi-copy.js";
8
+ import { eventPageUrlOf, registrationUi } from "../_shared/event-registration.js";
9
+ import { share as shareSheet } from "@himalaya/share";
10
+
11
+ // Offline-first (data-offline): the public events list is a read-through catalog —
12
+ // paint the last-synced rows from the on-device store first (instant, works offline),
13
+ // then revalidate from Wix and refresh the cache. DEGRADES GRACEFULLY: every local-db
14
+ // call is wrapped so a bundle that ships in an app which hasn't granted `local_database`
15
+ // (+ declared the `events` entity in its dataSchema) just falls back to today's
16
+ // online-only path — the try/catch is the seam that keeps this shared bundle safe.
17
+ const ENTITY = "events";
18
+ interface ListEventRow extends EventRow {
19
+ dateBadge: string; noDateBadge: boolean;
20
+ /** This card's verb (Register / RSVP / Buy Tickets / Join Waitlist) from the SAME rule the detail uses; hidden when none applies. */
21
+ actionLabel: string; noAction: boolean;
22
+ /** The event page URL (when the payload carries one) for Share. */
23
+ shareUrl: string;
24
+ }
25
+
26
+ // The day monogram is a title initial for undated events. Only an actual calendar
27
+ // date becomes a badge; derive it for old cached rows too, without a cache migration.
28
+ // The month must be the three-letter abbreviation: rows cached by an older worker on an
29
+ // Intl-less engine can hold a whole "11/10/2030, 12:00:00 PM" there.
30
+ function withDateBadge(row: EventRow): ListEventRow {
31
+ const dated = typeof row.month === "string" && /^[A-Z]{3}$/.test(row.month)
32
+ && /^(?:[1-9]|[12]\d|3[01])$/.test(row.day);
33
+ const known = row as Partial<ListEventRow>;
34
+ // Rows cached by an older build carry no registration data: they show no verb until a refresh, never a wrong one.
35
+ return { ...row, dateBadge: dated ? `${row.day}\n${row.month}` : "", noDateBadge: !dated,
36
+ actionLabel: known.actionLabel ?? "", noAction: known.noAction ?? true, shareUrl: known.shareUrl ?? "" };
37
+ }
38
+
39
+ /** The card's action, from the event's own registration (REGISTRATION + URLS fieldsets). Cancelled, ended,
40
+ * closed, sold-out and registration-less events offer none, so a card never promises "Register" the detail refuses. */
41
+ function withRegistration(raw: WixEvent, row: ListEventRow): ListEventRow {
42
+ const ui = registrationUi(raw, Date.now());
43
+ const offers = ui.state !== "notice" && ui.state !== "none" && ui.state !== "scheduled" && !!ui.label;
44
+ return { ...row, actionLabel: offers ? ui.label : "", noAction: !offers, shareUrl: eventPageUrlOf(raw) };
45
+ }
46
+
47
+ async function readCached(): Promise<ListEventRow[]> {
48
+ try { return ((await getAll(ENTITY)) as unknown as EventRow[]).map(withDateBadge); } catch { return []; }
49
+ }
50
+ async function writeCached(rows: EventRow[]): Promise<void> {
51
+ try { for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity); } catch { /* capability not granted → online-only */ }
52
+ }
53
+
54
+ interface S {
55
+ status: "loading" | "ready";
56
+ query: string; all: ListEventRow[]; results: ListEventRow[]; emptyText: string; countLabel: string;
57
+ errored: boolean; notErrored: boolean; isLoading: boolean; notLoading: boolean; noEmpty: boolean;
58
+ nextCursor?: string; complete?: boolean; total?: number; loadingMore?: boolean; pageError?: boolean; fromCache?: boolean;
59
+ }
60
+ let queryNow = new Date().toISOString();
61
+ const svc = defineBackendCollection<S, ListEventRow>("himiEvents", {
62
+ restorePagesOnLoad: true,
63
+ state: { status: "loading", query: "", all: [], results: [], emptyText: "", countLabel: "", errored: false, notErrored: true,
64
+ isLoading: true, notLoading: false, noEmpty: true },
65
+ source: {
66
+ id: row => row.id,
67
+ errorMessage: () => copyParam("events.errorText", "Events could not be loaded."),
68
+ async cached(criteria) {
69
+ // The list now OPENS on Upcoming, so the default view must keep its offline-first paint:
70
+ // serve the cache for it too, minus the rows that have finished.
71
+ const upcoming = criteria.filter === "value:Upcoming";
72
+ if (criteria.query || (criteria.filter !== "all" && !upcoming) || criteria.sort !== "default") return undefined;
73
+ const rows = await readCached();
74
+ return { items: upcoming ? rows.filter((row) => row.statusLabel !== "Past") : rows, nextCursor: "", metadata: { fromCache: true } };
75
+ },
76
+ async fetch(criteria, cursor) {
77
+ if (!cursor) queryNow = new Date().toISOString();
78
+ if (criteria.filter === "saved" && !criteria.savedIds.length) return { items: [], nextCursor: "" };
79
+ const filter: Record<string, unknown> = { status: { $ne: "DRAFT" } };
80
+ // Prefix, not exact: the placeholder says "Search events", and an exact-title match returned
81
+ // nothing for "Harvest" when the event is "Harvest Tasting".
82
+ if (criteria.query) filter.title = { $startsWith: criteria.query };
83
+ if (criteria.filter === "saved") filter.id = { $in: criteria.savedIds };
84
+ // Upcoming = not started yet OR not finished yet: an event in progress (a festival on its
85
+ // second day) is still on. The start-date arm is what keeps a START-ONLY event (no endDate
86
+ // — valid in Wix Events) in the list; a filter on endDate alone dropped it from both views.
87
+ // Past stays "has started", so an in-progress event may appear under both; its row is only
88
+ // marked "Past" once it has actually finished (`eventIsPast`).
89
+ if (criteria.filter === "value:Upcoming") {
90
+ filter.$or = [
91
+ { "dateAndTimeSettings.startDate": { $gte: queryNow } },
92
+ { "dateAndTimeSettings.endDate": { $gte: queryNow } },
93
+ ];
94
+ }
95
+ if (criteria.filter === "value:Past") filter["dateAndTimeSettings.startDate"] = { $lt: queryNow };
96
+ const res = await queryEvents({ limit: 50, offset: Number(cursor || 0), fields: ["DETAILS", "REGISTRATION", "URLS"], query: { filter,
97
+ sort: [{ fieldName: criteria.sort === "default" ? "dateAndTimeSettings.startDate" : "title", order: criteria.sort === "za" ? "DESC" : "ASC" }, { fieldName: "id", order: "ASC" }] } });
98
+ const raw = res.events ?? [];
99
+ const items = raw.filter(row => !!row.id).map(row => withRegistration(row, withDateBadge(normalizeEvent(row))));
100
+ await writeCached(items);
101
+ const metadata = (res as { pagingMetadata?: { total?: number } }).pagingMetadata;
102
+ return { items, ...offsetPage(cursor, raw.length, 50, metadata), metadata: { fromCache: false } };
103
+ },
104
+ },
105
+ apply(s, page) {
106
+ const loading = page.status === "loading", errored = page.status === "error";
107
+ return { ...s, status: loading ? "loading" : "ready", query: page.criteria.query, all: page.items, results: page.items,
108
+ nextCursor: page.nextCursor, complete: page.complete, total: page.total, loadingMore: page.loadingMore, pageError: page.pageError,
109
+ fromCache: page.metadata?.fromCache === true, errored, notErrored: !errored, isLoading: loading, notLoading: !loading,
110
+ noEmpty: true, countLabel: "", emptyText: errored ? copyParam("events.errorText", "Events could not be loaded.") : "" };
111
+ },
112
+ actions: {
113
+ // Share a card's event: its title and date line, plus the event page when the payload carried one.
114
+ share: async (s, arg) => {
115
+ const id = typeof arg === "string" ? arg : String((arg as { id?: unknown } | undefined)?.id ?? "");
116
+ const row = s.results.find(item => item.id === id);
117
+ if (!row) return undefined;
118
+ try { await shareSheet({ subject: row.title, text: [row.title, row.dateLine].filter(Boolean).join(" — "), ...(row.shareUrl ? { url: row.shareUrl } : {}) }); } catch { /* the sheet is best-effort: nothing to undo */ }
119
+ return undefined;
120
+ },
121
+ },
122
+ });
123
+ svc.load();
124
+ export { svc };
@@ -0,0 +1,225 @@
1
+ // Tier-5 bundle: himi-events — locally confirmed RSVP hub.
2
+ import { defineService } from "@himalaya/state";
3
+ import { dispatch } from "@himalaya/dispatch";
4
+ import { queryEvents, type WixEvent } from "@himalaya/wix-events";
5
+ import { getAll, upsert, type DbEntity } from "@himalaya/local-db";
6
+ import { confirmedRsvpIds, eventStartMillis, normalizeEvent, type EventRow } from "../_shared/himi-events";
7
+ import { stashCopy, copyParam, copyTemplate } from "../_shared/himi-copy.js";
8
+ import { memberAccess } from "../_shared/member-access.js";
9
+ import { readAccess, assertReadAccess, readAccessDenied, readSignInFlags, NO_READ_SIGN_IN } from "../_shared/member-read.js";
10
+
11
+ // Offline-first (data-offline): My Events is a read-through over the same `events`
12
+ // catalog the list caches — paint the last-synced rows (filtered to this device's
13
+ // confirmed RSVP ids from KV) first, then revalidate from Wix and refresh the cache.
14
+ // DEGRADES GRACEFULLY: every local-db call is wrapped so a bundle that ships in an app
15
+ // which hasn't granted `local_database` (+ declared the `events` entity) just falls
16
+ // back to today's online-only path.
17
+ const ENTITY = "events";
18
+ interface CachedEventRow extends EventRow {
19
+ /** Canonical Wix start instant used to derive relative copy on every paint. */
20
+ startMillis?: number;
21
+ /** Static Wix status, kept separate from time-sensitive display copy. */
22
+ canonicalStatus?: string;
23
+ }
24
+ async function readCached(): Promise<CachedEventRow[]> {
25
+ try { return (await getAll(ENTITY)) as unknown as CachedEventRow[]; } catch { return []; }
26
+ }
27
+ async function writeCached(rows: CachedEventRow[]): Promise<void> {
28
+ try { for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity); } catch { /* capability not granted → online-only */ }
29
+ }
30
+
31
+ interface S {
32
+ signInRequired: boolean; noSignIn: boolean; signInScreenId: string;
33
+ status: "loading" | "ready";
34
+ events: EventRow[];
35
+ emptyText: string;
36
+ countLabel: string;
37
+ identityLine: string;
38
+ verificationUnavailable: boolean;
39
+ errored: boolean;
40
+ notErrored: boolean;
41
+ isLoading: boolean;
42
+ notLoading: boolean;
43
+ noEmpty: boolean;
44
+ }
45
+
46
+ function derive(s: S): S {
47
+ return {
48
+ ...s,
49
+ isLoading: s.status === "loading",
50
+ notLoading: s.status !== "loading",
51
+ notErrored: !s.errored,
52
+ noEmpty: s.status === "loading" || s.errored || s.events.length > 0,
53
+ emptyText: s.events.length
54
+ ? ""
55
+ : (s.errored
56
+ ? copyParam("myEvents.errorText", "My Events could not be loaded.")
57
+ : copyParam("myEvents.emptyText", "No confirmed RSVPs on this device yet.")),
58
+ countLabel: s.events.length
59
+ ? `${s.events.length} ${s.verificationUnavailable ? "saved" : "confirmed"} ${s.events.length === 1 ? "event" : "events"}`
60
+ : "",
61
+ };
62
+ }
63
+
64
+ async function identityLine(): Promise<string> {
65
+ try {
66
+ const identity = await dispatch("himi.wix.memberIdentity") as { email?: string } | null;
67
+ return identity?.email
68
+ ? copyTemplate("myEvents.signedInAs", "Signed in as {email}", { email: identity.email })
69
+ : copyParam("myEvents.identityGuest", "RSVPs you confirm on this device appear here.");
70
+ } catch {
71
+ return copyParam("myEvents.identityGuest", "RSVPs you confirm on this device appear here.");
72
+ }
73
+ }
74
+
75
+ function imminentLabel(start: number | undefined): string {
76
+ if (!start) return "";
77
+ const minutes = Math.ceil((start - Date.now()) / 60000);
78
+ if (minutes <= 0) return "";
79
+ if (minutes < 60) return copyTemplate("myEvents.startsInMinutes", "Starts in {count} min", { count: minutes });
80
+ const hours = Math.ceil(minutes / 60);
81
+ if (hours <= 24) return copyTemplate("myEvents.startsInHours", "Starts in {count}h", { count: hours });
82
+ const days = Math.ceil(hours / 24);
83
+ if (days <= 14) return copyTemplate("myEvents.startsInDays", "Starts in {count}d", { count: days });
84
+ return "";
85
+ }
86
+
87
+ function cachedEventRow(event: WixEvent): CachedEventRow {
88
+ const row = normalizeEvent(event);
89
+ return { ...row, startMillis: eventStartMillis(event), canonicalStatus: row.status };
90
+ }
91
+
92
+ function displayEventRow(event: CachedEventRow): CachedEventRow {
93
+ const status = event.canonicalStatus ?? event.status;
94
+ return { ...event, status: [imminentLabel(event.startMillis), status].filter(Boolean).join(" · ") };
95
+ }
96
+
97
+ function unverifiedEvent(event: CachedEventRow): CachedEventRow {
98
+ return {
99
+ ...event,
100
+ status: [event.status, copyParam("myEvents.rsvpUnverified", "Saved RSVP · verification unavailable")].filter(Boolean).join(" · "),
101
+ };
102
+ }
103
+
104
+ /** Verify device-local candidates against the current member. Member-only mode
105
+ * requires successful verification; standalone mode retains failed probes as
106
+ * explicitly unverified device-local history. */
107
+ async function confirmRsvps(candidates: CachedEventRow[], memberOnly = false): Promise<{ events: CachedEventRow[]; verificationUnavailable: boolean }> {
108
+ // Raw wixApi chokepoint rather than a generated client: the member RSVP read lives in
109
+ // events **v2**, and `@himalaya/wix-events` is the v1 domain module. Adding a
110
+ // `wix-events-v2` specifier is not an option — the umbrella package deliberately
111
+ // forbids versioned subpaths (its own test: "no -vN subpaths"; note wix-members maps
112
+ // to members-v1 with an UNversioned name), and one read is not worth changing the
113
+ // public SDK surface for. This is the documented escape hatch for an endpoint the
114
+ // domain module doesn't carry.
115
+ const wixApi = (globalThis as { himalaya?: { wixApi?: { call: (m: string, p: string, b?: unknown) => Promise<unknown> } } }).himalaya?.wixApi;
116
+ if (!wixApi) return { events: candidates.map(unverifiedEvent), verificationUnavailable: candidates.length > 0 };
117
+ const checked = await Promise.all(candidates.map(async (event) => {
118
+ try {
119
+ const res = await wixApi.call("GET", `/events/v2/rsvps/current?eventId=${encodeURIComponent(event.id)}`);
120
+ const rsvps = (res as { rsvps?: Array<{ status?: string }> }).rsvps ?? [];
121
+ // No RSVP at all, or every one cancelled ⇒ this is stale device state.
122
+ const held = rsvps.some((r) => !/cancel|declin/i.test(r.status ?? ""));
123
+ return {
124
+ event: held ? { ...event, status: [event.status, copyParam("myEvents.rsvpConfirmed", "RSVP confirmed")].filter(Boolean).join(" · ") } : null,
125
+ verificationUnavailable: false,
126
+ };
127
+ } catch (error) {
128
+ // Device candidates carry no member ownership proof until this read succeeds.
129
+ if (memberOnly) throw error;
130
+ // Fail-open, but never claim backend confirmation while its member-readable
131
+ // probe is unavailable. The device id remains a candidate, explicitly labeled.
132
+ return { event: unverifiedEvent(event), verificationUnavailable: true };
133
+ }
134
+ }));
135
+ return {
136
+ events: checked.map((result) => result.event).filter((event): event is CachedEventRow => event !== null),
137
+ verificationUnavailable: checked.some((result) => result.verificationUnavailable),
138
+ };
139
+ }
140
+
141
+ const INITIAL: S = derive({
142
+ ...NO_READ_SIGN_IN, signInScreenId: "himi_account",
143
+ status: "loading",
144
+ events: [],
145
+ emptyText: "",
146
+ countLabel: "",
147
+ identityLine: "",
148
+ verificationUnavailable: false,
149
+ errored: false,
150
+ notErrored: true,
151
+ isLoading: true,
152
+ notLoading: false,
153
+ noEmpty: true,
154
+ });
155
+ let memberOnlyRequested = false;
156
+ let loadVersion = 0;
157
+ const svc = defineService<S, { prepare: (s: S) => S; load: (s: S, arg?: unknown) => Promise<S | undefined> }>("himiMyEvents", {
158
+ state: INITIAL,
159
+ actions: {
160
+ prepare: (s) => ({ ...s, ...INITIAL }),
161
+ load: async (s, arg): Promise<S | undefined> => {
162
+ stashCopy(arg);
163
+ const version = ++loadVersion;
164
+ const options = arg as { memberOnly?: unknown; signInScreenId?: unknown } | undefined;
165
+ if (options?.memberOnly !== undefined) memberOnlyRequested = options.memberOnly === "1";
166
+ const memberOnly = memberOnlyRequested;
167
+ const clean = { ...INITIAL, signInScreenId: options?.signInScreenId === "himi_sign_in" ? "himi_sign_in" : s.signInScreenId };
168
+ await svc.prepare();
169
+ try {
170
+ const member = memberOnly ? await readAccess() : null;
171
+ if (memberOnly && !member?.member.email) throw new Error("Unauthenticated: sign in to see your events");
172
+ const confirmed = new Set(confirmedRsvpIds());
173
+ const identity = await identityLine();
174
+ // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
175
+ // Device-local candidates have no member ownership proof. Branded must
176
+ // verify them online rather than show a previous member's cached RSVP list.
177
+ const cached = memberOnly ? [] : await readCached();
178
+ const cachedEvents = cached.filter((event) => confirmed.has(event.id)).map(displayEventRow);
179
+ const base = cached.length
180
+ ? derive({ ...clean, status: "ready", errored: false, events: cachedEvents, identityLine: identity, verificationUnavailable: cachedEvents.length > 0 })
181
+ : clean;
182
+ // 2) Revalidate from Wix and refresh the cache.
183
+ try {
184
+ const res = await queryEvents({ limit: 50 });
185
+ const all = ((res as unknown as { events?: WixEvent[] }).events ?? []).map(cachedEventRow);
186
+ if (member) await assertReadAccess(member);
187
+ if (version !== loadVersion) return undefined;
188
+ await writeCached(all);
189
+ // Phase 3c — make each row AUTHORITATIVE. The device list is only a candidate
190
+ // set: it never forgets, so an RSVP cancelled elsewhere (web, or by the
191
+ // business) would otherwise show here forever. Confirm each candidate against
192
+ // Wix and drop the ones the member no longer holds.
193
+ //
194
+ // Per-event by necessity, not by choice: a member CANNOT enumerate their own
195
+ // RSVPs. Verified live against a real member token — `queryRsvps` (cross-event)
196
+ // 403s "WIX_EVENTS.READ_RSVP permission required", `listOrders` 403s
197
+ // READ_ORDERS, and `/rsvps/current` 400s without an eventId. Only the
198
+ // single-event read is member-readable, so the fan-out below IS the ceiling
199
+ // until those member scopes exist server-side.
200
+ const candidates = all.filter((event) => confirmed.has(event.id)).map(displayEventRow);
201
+ const confirmation = await confirmRsvps(candidates, memberOnly);
202
+ if (member) await assertReadAccess(member);
203
+ if (version !== loadVersion) return undefined;
204
+ return derive({ ...base, status: "ready", errored: false, events: confirmation.events, identityLine: identity, verificationUnavailable: confirmation.verificationUnavailable });
205
+ } catch (error) {
206
+ if (memberOnly && readAccessDenied(error)) throw error;
207
+ if (member) await assertReadAccess(member);
208
+ if (version !== loadVersion) return undefined;
209
+ // Offline / fetch failure: keep the cached rows instead of a blank error state.
210
+ return cached.length
211
+ ? base
212
+ : derive({ ...clean, status: "ready", errored: true, events: [], identityLine: identity });
213
+ }
214
+ } catch (error) {
215
+ const failure = memberOnly && !(await memberAccess()).email ? new Error("Unauthenticated: sign in to see your events") : error;
216
+ const flags = await readSignInFlags(failure);
217
+ return version === loadVersion ? derive({ ...clean, ...flags, status: "ready", errored: true, events: [] }) : undefined;
218
+ }
219
+ },
220
+ },
221
+ });
222
+ // Wait for the descriptor's load action to select member-only or device-local scope.
223
+ // An eager unconfigured read could briefly expose guest KV before Branded opts in.
224
+ svc.prepare();
225
+ export { svc };
@@ -0,0 +1,230 @@
1
+ import { withOnlineWrites, offlineWritesEnabled } from "../_shared/online-actions.js";
2
+ // Tier-5 bundle: himi-events — member RSVP flow.
3
+ import { defineService as registerService } from "@himalaya/state";
4
+ import { dispatch } from "@himalaya/dispatch";
5
+ import { createRsvp, getEvent, type WixEvent } from "@himalaya/wix-events";
6
+ import { displayName, getMyData, type WixMyData } from "@himalaya/wix-users";
7
+ import { upsert as dbUpsert, remove as dbRemove, enqueue as dbEnqueue, type DbEntity } from "@himalaya/local-db";
8
+ import { currentInputId, eventLocation, eventWhen, rememberRsvp } from "../_shared/himi-events";
9
+ import { stashCopy, copyParam } from "../_shared/himi-copy.js";
10
+ import { isBridgeUnavailable } from "../_shared/owner-load-error.js";
11
+
12
+ // Offline-first (data-offline): the RSVP write is WRITE-BEHIND against the `rsvps`
13
+ // entity — the row is written OPTIMISTICALLY before the Wix POST, then the create is
14
+ // attempted; if the bridge/network is unreachable the mutation is ENQUEUED for replay
15
+ // on reconnect (the existing KV rsvp-id tracking is left untouched). Every local-db call
16
+ // is wrapped (try/catch) so a build without the `local_database` grant behaves exactly
17
+ // as before (online-only, no cache/queue).
18
+ const ENTITY = "rsvps";
19
+ async function cachePut(row: DbEntity): Promise<void> { try { await dbUpsert(ENTITY, row); } catch { /* capability not granted */ } }
20
+ async function cacheDrop(id: string): Promise<void> { try { await dbRemove(ENTITY, id); } catch { /* capability not granted */ } }
21
+ async function queueWrite(actionId: string, params: Record<string, string>): Promise<void> { try { await dbEnqueue(actionId, params); } catch { /* capability not granted */ } }
22
+
23
+ interface S {
24
+ status: "loading" | "ready";
25
+ id: string;
26
+ title: string;
27
+ when: string;
28
+ location: string;
29
+ email: string;
30
+ password: string;
31
+ isMember: boolean;
32
+ notMember: boolean;
33
+ identityLine: string;
34
+ message: string;
35
+ successMessage: string;
36
+ noSuccess: boolean;
37
+ canRsvp: boolean;
38
+ cannotRsvp: boolean;
39
+ /** Hides a guest's RSVP button, which opens a sign-in screen: shown only for a guest with
40
+ * an event to RSVP to, as `cannotRsvp` requires an event for a member's. */
41
+ hideGuestRsvp: boolean;
42
+ errored: boolean;
43
+ notErrored: boolean;
44
+ isLoading: boolean;
45
+ notLoading: boolean;
46
+ noEmpty: boolean;
47
+ emptyText: string;
48
+ }
49
+
50
+ function inputId(): string {
51
+ return currentInputId(["himi_rsvp_"]);
52
+ }
53
+
54
+ function strOf(arg: unknown): string {
55
+ if (typeof arg === "string") return arg;
56
+ const a = arg as { value?: string; text?: string } | undefined;
57
+ return a?.value ?? a?.text ?? "";
58
+ }
59
+
60
+ function rsvpErrorCopy(msg: string): string {
61
+ if (/RSVPS?_CLOSED/i.test(msg)) return copyParam("rsvp.errorClosed", "RSVPs are closed for this event.");
62
+ if (/RSVPS_NOT_STARTED/i.test(msg)) return copyParam("rsvp.errorNotStarted", "RSVPs have not opened yet.");
63
+ if (/(GUEST|RSVP)_LIMIT_(EXCEEDED|REACHED)|FULL/i.test(msg)) return copyParam("rsvp.errorFull", "This event is full.");
64
+ if (/(GUEST|MEMBER)(_EMAIL)?_ALREADY_REGISTERED/i.test(msg)) return copyParam("rsvp.errorAlreadyRegistered", "You are already registered.");
65
+ if (/WAITING_LIST_UNAVAILABLE/i.test(msg)) return copyParam("rsvp.errorWaitlistFull", "The waiting list is full.");
66
+ return copyParam("rsvp.errorGeneric", "Could not RSVP. Try again.");
67
+ }
68
+
69
+ function derive(s: S): S {
70
+ const hasEvent = !!s.title;
71
+ const hasSuccess = !!s.successMessage;
72
+ const canRsvp = s.isMember && hasEvent && !hasSuccess;
73
+ return {
74
+ ...s,
75
+ isLoading: s.status === "loading",
76
+ notLoading: s.status !== "loading",
77
+ isMember: s.isMember,
78
+ notMember: !s.isMember,
79
+ canRsvp,
80
+ cannotRsvp: !canRsvp,
81
+ hideGuestRsvp: s.isMember || !hasEvent,
82
+ noSuccess: !hasSuccess,
83
+ notErrored: !s.errored,
84
+ noEmpty: s.status === "loading" || s.errored || hasEvent,
85
+ emptyText: hasEvent
86
+ ? ""
87
+ : (s.errored
88
+ ? copyParam("rsvp.errorText", "RSVP could not be loaded.")
89
+ : copyParam("rsvp.noEventText", "No event selected.")),
90
+ };
91
+ }
92
+
93
+ async function signedInEmail(): Promise<string> {
94
+ try {
95
+ const identity = await dispatch("himi.wix.memberIdentity") as { email?: string } | null;
96
+ return typeof identity?.email === "string" ? identity.email : "";
97
+ } catch {
98
+ return "";
99
+ }
100
+ }
101
+
102
+ async function probeMember(s: S): Promise<S> {
103
+ const storedEmail = await signedInEmail();
104
+ if (storedEmail) {
105
+ return derive({ ...s, isMember: true, email: storedEmail, identityLine: storedEmail, message: "" });
106
+ }
107
+ try {
108
+ const data = await getMyData();
109
+ const email = data.email || data.contactEmail || s.email;
110
+ return derive({
111
+ ...s,
112
+ isMember: true,
113
+ email,
114
+ identityLine: displayName(data) || email || copyParam("rsvp.signedIn", "Signed in"),
115
+ message: "",
116
+ });
117
+ } catch {
118
+ return derive({ ...s, isMember: false, identityLine: copyParam("rsvp.identityGuest", "Sign in to RSVP.") });
119
+ }
120
+ }
121
+
122
+ function contactName(dataLine: string): { first: string; last: string } {
123
+ const parts = dataLine.trim().split(/\s+/).filter(Boolean);
124
+ if (!parts.length) return { first: "Himi", last: "Member" };
125
+ if (parts.length === 1) return { first: parts[0], last: "Member" };
126
+ return { first: parts[0], last: parts.slice(1).join(" ") };
127
+ }
128
+
129
+ const defineService = withOnlineWrites(registerService, ["rsvp", "signIn"], { derive, secretFields: ["password"] });
130
+ const svc = defineService<S, {
131
+ load: (s: S, arg?: unknown) => Promise<S>;
132
+ setEmail: (s: S, arg?: unknown) => S;
133
+ setPassword: (s: S, arg?: unknown) => S;
134
+ signIn: (s: S) => Promise<S>;
135
+ rsvp: (s: S) => Promise<S>;
136
+ }>("himiEventsRsvp", {
137
+ state: derive({
138
+ status: "loading",
139
+ id: inputId(),
140
+ title: "",
141
+ when: "",
142
+ location: "",
143
+ email: "",
144
+ password: "",
145
+ isMember: false,
146
+ notMember: true,
147
+ identityLine: "Sign in to RSVP.",
148
+ message: "",
149
+ successMessage: "",
150
+ noSuccess: true,
151
+ canRsvp: false,
152
+ cannotRsvp: true,
153
+ hideGuestRsvp: true,
154
+ errored: false,
155
+ notErrored: true,
156
+ isLoading: true,
157
+ notLoading: false,
158
+ noEmpty: true,
159
+ emptyText: "",
160
+ }),
161
+ actions: {
162
+ load: async (s, arg) => {
163
+ stashCopy(arg);
164
+ const id = s.id || inputId();
165
+ let next = await probeMember(derive({ ...s, id, status: "loading", errored: false, message: "" }));
166
+ if (!id) return derive({ ...next, status: "ready", errored: true });
167
+ try {
168
+ const res = await getEvent(id);
169
+ const e = ((res as unknown as { event?: WixEvent }).event ?? res) as WixEvent;
170
+ return derive({
171
+ ...next,
172
+ status: "ready",
173
+ errored: false,
174
+ title: e.title || "Event",
175
+ when: eventWhen(e),
176
+ location: eventLocation(e),
177
+ });
178
+ } catch {
179
+ return derive({ ...next, status: "ready", errored: true, title: "" });
180
+ }
181
+ },
182
+ setEmail: (s, arg) => derive({ ...s, email: strOf(arg), message: "" }),
183
+ setPassword: (s, arg) => derive({ ...s, password: strOf(arg), message: "" }),
184
+ signIn: async (s) => {
185
+ if (!s.email || !s.password) return derive({ ...s, message: copyParam("rsvp.validationEmailPassword", "Enter your email and password.") });
186
+ try {
187
+ await dispatch("himi.wix.signInDirect", { email: s.email, password: s.password });
188
+ const p = await probeMember({ ...s, isMember: true, identityLine: s.email });
189
+ return derive({ ...p, password: "", message: p.isMember ? copyParam("rsvp.signedInReady", "Signed in. You can RSVP now.") : copyParam("rsvp.signInCheckDetails", "Sign in failed. Check your details.") });
190
+ } catch {
191
+ return derive({ ...s, password: "", message: copyParam("rsvp.signInFailed", "Sign in failed. Try again.") });
192
+ }
193
+ },
194
+ rsvp: async (s) => {
195
+ if (!s.id) return derive({ ...s, message: copyParam("rsvp.noEventText", "No event selected.") });
196
+ if (!s.isMember) return derive({ ...s, message: copyParam("rsvp.needsSignIn", "Sign in before confirming your RSVP.") });
197
+ // These reads are individually failure-safe (getMyData is .catch-guarded,
198
+ // signedInEmail swallows errors), so computing them up front lets us write the
199
+ // optimistic cache row before the Wix POST without changing online behavior.
200
+ const my = await getMyData().catch(() => ({ email: s.email } as WixMyData));
201
+ const email = (await signedInEmail()) || my.email || my.contactEmail || s.email;
202
+ const name = contactName(displayName(my) || email);
203
+ const guestEmail = email || "member@example.com";
204
+ // Optimistic local write — the RSVP row lands in the cache before the Wix POST.
205
+ const rsvpRow = (id: string): DbEntity => ({ id, eventId: s.id, firstName: name.first, lastName: name.last, email: guestEmail, status: "YES", title: s.title });
206
+ const localId = s.id;
207
+ if (!offlineWritesEnabled) await cachePut(rsvpRow(localId));
208
+ try {
209
+ const res = await createRsvp(s.id, name.first, name.last, guestEmail, "YES");
210
+ // Reconcile the optimistic local id with the server-assigned rsvp id.
211
+ const serverId = res.rsvp?.id;
212
+ if (offlineWritesEnabled) await cachePut(rsvpRow(serverId || localId));
213
+ else if (serverId && serverId !== localId) { await cacheDrop(localId); await cachePut(rsvpRow(serverId)); }
214
+ rememberRsvp(s.id);
215
+ return derive({ ...s, successMessage: copyParam("rsvp.successMessage", "You are going. Added to My Events."), message: "" });
216
+ } catch (e) {
217
+ if (!offlineWritesEnabled && isBridgeUnavailable(e)) {
218
+ // Offline / no bridge: the optimistic cache row already shows; queue the
219
+ // write to replay (WriteQueue, idempotent) when connectivity returns.
220
+ await queueWrite("tier5.himiEventsRsvp.rsvp", { id: s.id, firstName: name.first, lastName: name.last, email: guestEmail, status: "YES" });
221
+ return derive({ ...s, successMessage: "RSVP saved offline — will sync when you reconnect.", message: "" });
222
+ }
223
+ const msg = String((e as { message?: string })?.message || e);
224
+ return derive({ ...s, message: rsvpErrorCopy(msg) });
225
+ }
226
+ },
227
+ },
228
+ });
229
+ svc.load();
230
+ export { svc };