@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.
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/builder.d.ts +3 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/validator.d.ts +6 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/wix-sdk/media/src/rendition.d.ts +6 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +1 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/screens.mjs +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +1 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-events.mjs +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-media.mjs +22 -4
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-rich-content.mjs +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-stores-collections.mjs +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-stores.mjs +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-video.mjs +4 -0
- package/dist/browser-plane/assets.json +5 -5
- package/dist/browser-plane/preview-deferred/{155f61519885c85d61a39fa595197071a3ca07680da56055ccb1dcff2e709cd1.bin → 4ef4d326496b4d7809746936207067b4c921f5db9878ecc7030aa3a9e4d2aaeb.bin} +1 -1
- package/dist/browser-plane/sw.js +5 -5
- package/dist/cli.mjs +4098 -3351
- package/dist/preview-assets.generated.bin +0 -0
- package/guides/component-reference.json +1 -1
- package/guides/component-reference.md +2 -0
- package/guides/designing-himi-screens.md +4 -0
- package/guides/himi-skill.md +6 -0
- package/guides/image-preview.md +92 -0
- package/guides/index.json +7 -0
- package/guides/release-notes.md +6 -0
- package/guides/sdk-reference.json +9 -2
- package/package.json +2 -2
- package/template-icons/wholesale-store.png +0 -0
- package/templates/beauty-salon-owner/dev/index.ts +7 -0
- package/templates/community-club-owner/dev/index.ts +7 -0
- package/templates/events-meetups-owner/dev/index.ts +7 -0
- package/templates/gym-fitness-owner/dev/index.ts +7 -0
- package/templates/nonprofit-cause-owner/dev/index.ts +7 -0
- package/templates/owner-lite/dev/index.ts +7 -0
- package/templates/podcast-creator-owner/dev/index.ts +7 -0
- package/templates/portfolio-creative-owner/dev/index.ts +7 -0
- package/templates/restaurant-owner/dev/index.ts +7 -0
- package/templates/retail-store-owner/dev/index.ts +7 -0
- package/templates/wholesale-store/README.md +53 -0
- package/templates/wholesale-store/config.ts +247 -0
- package/templates/wholesale-store/dev/index.ts +12194 -0
- package/templates/wholesale-store/himalaya.content.json +43 -0
- package/templates/wholesale-store/himalaya.template.json +14 -0
- package/templates/wholesale-store/icon.png +0 -0
- package/templates/wholesale-store/platforms.json +1 -0
- package/templates/wholesale-store/tier5-src/_shared/app-locale.ts +61 -0
- package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +279 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-copy.ts +40 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-history.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-model.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-presenter.ts +576 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +148 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-contract.ts +228 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +194 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +252 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +423 -0
- package/templates/wholesale-store/tier5-src/_shared/detail-presence.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/empty-flags.ts +33 -0
- package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +508 -0
- package/templates/wholesale-store/tier5-src/_shared/exclusive-writes.ts +66 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-account.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-copy.ts +89 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-categories.ts +108 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +22 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +57 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store.ts +7 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-text.ts +24 -0
- package/templates/wholesale-store/tier5-src/_shared/hosted-checkout.ts +70 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-presentation.ts +207 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-worker.ts +125 -0
- package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +68 -0
- package/templates/wholesale-store/tier5-src/_shared/live-session.ts +172 -0
- package/templates/wholesale-store/tier5-src/_shared/local-preferences.ts +38 -0
- package/templates/wholesale-store/tier5-src/_shared/member-access.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-account-routes.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-orders.ts +8 -0
- package/templates/wholesale-store/tier5-src/_shared/member-screen.ts +99 -0
- package/templates/wholesale-store/tier5-src/_shared/online-actions.ts +76 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-editor-value.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-load-error.ts +348 -0
- package/templates/wholesale-store/tier5-src/_shared/payment-setup.ts +6 -0
- package/templates/wholesale-store/tier5-src/_shared/read-service.ts +255 -0
- package/templates/wholesale-store/tier5-src/_shared/restaurant-ordering.ts +201 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-body.ts +78 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-content-link.ts +34 -0
- package/templates/wholesale-store/tier5-src/_shared/sign-in-sheet.ts +18 -0
- package/templates/wholesale-store/tier5-src/_shared/store-order-presentation.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/store-product-info.ts +50 -0
- package/templates/wholesale-store/tier5-src/business-chat/index.ts +724 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +602 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-order/index.ts +472 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-orders/index.ts +327 -0
- package/templates/wholesale-store/tier5-src/himi-store-account/index.ts +998 -0
- package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +889 -0
- package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +68 -0
- package/templates/wholesale-store/tier5-src/himi-store-shop/index.ts +150 -0
- package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +507 -0
- package/templates/wholesale-store/tier5-src/wix-spaces-collection-detail/index.ts +195 -0
- package/templates/wholesale-store/tokens.json +340 -0
- package/templates/yoga-studio-owner/dev/index.ts +7 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { defineService, type ServiceDefinition } from "@himalaya/state";
|
|
2
|
+
import { createIapCommerce, type IapCommerce, type IapOrderAdapter } from "@himalaya/iap-checkout";
|
|
3
|
+
import { iapPriceFields, type IapCatalogItem } from "@himalaya/iap";
|
|
4
|
+
import { iapPriceCopy, resetUnhydratedKeysOnOlderRuntime } from "./iap-worker.js";
|
|
5
|
+
|
|
6
|
+
// Presentation only. Checkout, mapping, cache, session and refresh policy stay in the shared flow.
|
|
7
|
+
export function withIapPresentation<S extends object>(options: {
|
|
8
|
+
register?: typeof defineService;
|
|
9
|
+
/** The verticals this screen sells; none for a screen that only shows prices. */
|
|
10
|
+
adapters?: readonly IapOrderAdapter[];
|
|
11
|
+
onCreate?(commerce: IapCommerce): void;
|
|
12
|
+
onContent?(state: S): void;
|
|
13
|
+
items(state: S): IapCatalogItem[];
|
|
14
|
+
/** `resolving` is true while the checkout guard has no answer yet (a cold boot, a refresh): a
|
|
15
|
+
* screen reads it as loading, never as "not allowed". */
|
|
16
|
+
present(state: S, price: (id: string, commercePrice?: string) => string, allowed: (id: string) => boolean, appleIapOrResolving: (id: string) => boolean, resolving: (id: string) => boolean): S;
|
|
17
|
+
contentActions: string[];
|
|
18
|
+
/** Defaults to load/refresh/retry; mutations can explicitly request fresh mapping. */
|
|
19
|
+
forcePriceRefreshActions?: string[];
|
|
20
|
+
concurrentPublishActions?: string[];
|
|
21
|
+
/** Override the commerce factory in focused worker tests. */
|
|
22
|
+
commerceFactory?: typeof createIapCommerce;
|
|
23
|
+
transientKeys: (keyof S & string)[];
|
|
24
|
+
prefix: string;
|
|
25
|
+
}): typeof defineService {
|
|
26
|
+
return ((name: string, definition: ServiceDefinition<S>) => {
|
|
27
|
+
let queuePublish = () => {};
|
|
28
|
+
const commerce = (options.commerceFactory ?? createIapCommerce)({ adapters: options.adapters, onChange: () => queuePublish() });
|
|
29
|
+
options.onCreate?.(commerce);
|
|
30
|
+
let items: IapCatalogItem[] = [];
|
|
31
|
+
let loadedItemsKey = "";
|
|
32
|
+
const settledViews = new Map<string, { commerceDisplayPrice?: string; view: ReturnType<IapCommerce["pricing"]["view"]> }>();
|
|
33
|
+
const forcePriceRefreshActions = new Set(options.forcePriceRefreshActions ?? options.contentActions.filter(action => ["load", "refresh", "retry"].includes(action)));
|
|
34
|
+
let contentVersion = 0;
|
|
35
|
+
let actionVersion = 0;
|
|
36
|
+
let activeActions = 0;
|
|
37
|
+
let activeConcurrentPublishActions = 0;
|
|
38
|
+
let actionWaiters: Array<() => void> = [];
|
|
39
|
+
let publishQueued = false;
|
|
40
|
+
// pollDirective() arms its interval as a side effect. Keep a directive from a
|
|
41
|
+
// projection that loses a commit race so the retry can still publish it.
|
|
42
|
+
let uncommittedPollDirective: ReturnType<IapCommerce["pollDirective"]>;
|
|
43
|
+
let uncommittedPollVersion = 0;
|
|
44
|
+
// The committed state, read when a publish runs. Assigned once the service exists, so the
|
|
45
|
+
// service's own initializer never refers to it.
|
|
46
|
+
let committed: () => S = () => definition.state;
|
|
47
|
+
queuePublish = () => {
|
|
48
|
+
if (publishQueued) return;
|
|
49
|
+
publishQueued = true;
|
|
50
|
+
// Tier-5 workers have no timer globals. A microtask is enough here: if the
|
|
51
|
+
// action that caused the price update is still in flight, iapPublish's
|
|
52
|
+
// action-version check queues another publish after that action commits.
|
|
53
|
+
const publish = () => {
|
|
54
|
+
publishQueued = false;
|
|
55
|
+
void service.iapPublish();
|
|
56
|
+
};
|
|
57
|
+
void Promise.resolve().then(publish);
|
|
58
|
+
};
|
|
59
|
+
const project = (state: S, retainedPoll?: ReturnType<IapCommerce["pollDirective"]>): S => {
|
|
60
|
+
const presentationView = (id: string, commercePrice?: string) => {
|
|
61
|
+
const item = items.find(item => item.reference.id === id);
|
|
62
|
+
const reference = item?.reference ?? { kind: "storesProduct", id };
|
|
63
|
+
const key = `${reference.kind}:${reference.id}`;
|
|
64
|
+
const current = commerce.pricing.view(reference);
|
|
65
|
+
const cached = settledViews.get(key);
|
|
66
|
+
const displayPrice = commercePrice ?? item?.commerceDisplayPrice;
|
|
67
|
+
if (current.route === "resolving" && cached && cached.commerceDisplayPrice === displayPrice) return cached.view;
|
|
68
|
+
if (current.route !== "resolving" && item) settledViews.set(key, { commerceDisplayPrice: item.commerceDisplayPrice, view: current });
|
|
69
|
+
return current;
|
|
70
|
+
};
|
|
71
|
+
const price = (id: string, commercePrice?: string) => {
|
|
72
|
+
const item = items.find(item => item.reference.id === id);
|
|
73
|
+
if (!item) return "";
|
|
74
|
+
const view = presentationView(id, commercePrice);
|
|
75
|
+
if (view.route === "resolving") return iapPriceCopy(options.prefix).loading;
|
|
76
|
+
return view.route === "disabled" || view.route === "regular" ? commercePrice ?? item.commerceDisplayPrice ?? "" : iapPriceFields(view, iapPriceCopy(options.prefix)).priceText;
|
|
77
|
+
};
|
|
78
|
+
const allowed = (id: string) => commerce.pricing.checkoutGuard({ kind: "storesProduct", id }).allowed;
|
|
79
|
+
const resolving = (id: string) => commerce.pricing.checkoutGuard({ kind: "storesProduct", id }).route === "resolving";
|
|
80
|
+
const appleIapOrResolving = (id: string) => ["appleIap", "resolving", "unavailable"].includes(presentationView(id).route);
|
|
81
|
+
// Re-evaluate the cadence first. A checkout can enter/leave due work while a prior
|
|
82
|
+
// projection is waiting to retry; a fresh directive supersedes the retained one.
|
|
83
|
+
const poll = commerce.pollDirective(`${name}.iapPoll`) ?? retainedPoll;
|
|
84
|
+
return { ...options.present(state, price, allowed, appleIapOrResolving, resolving), ...(poll ? { _poll: poll } : {}) };
|
|
85
|
+
};
|
|
86
|
+
const mergeConcurrent = (before: S, next: S, current: S): S => {
|
|
87
|
+
if (current === before) return next;
|
|
88
|
+
const merged = { ...current } as Record<string, unknown>;
|
|
89
|
+
const previous = before as Record<string, unknown>;
|
|
90
|
+
const changed = next as Record<string, unknown>;
|
|
91
|
+
for (const key of new Set([...Object.keys(previous), ...Object.keys(changed)])) {
|
|
92
|
+
if (JSON.stringify(previous[key]) === JSON.stringify(changed[key])) continue;
|
|
93
|
+
if (Object.prototype.hasOwnProperty.call(changed, key)) merged[key] = changed[key];
|
|
94
|
+
else delete merged[key];
|
|
95
|
+
}
|
|
96
|
+
return merged as S;
|
|
97
|
+
};
|
|
98
|
+
const actions = Object.fromEntries(Object.entries(definition.actions ?? {}).map(([action, reduce]) => [action, (state: S, ...args: never[]) => {
|
|
99
|
+
actionVersion++;
|
|
100
|
+
activeActions++;
|
|
101
|
+
const concurrentPublish = options.concurrentPublishActions?.includes(action) ?? false;
|
|
102
|
+
if (concurrentPublish) activeConcurrentPublishActions++;
|
|
103
|
+
const content = options.contentActions.includes(action);
|
|
104
|
+
const version = action === "load" ? ++contentVersion : contentVersion;
|
|
105
|
+
const presentResult = (next: S | undefined) => {
|
|
106
|
+
// scopeLanded is the completion of the active load, not a stale load result. It
|
|
107
|
+
// must publish even if another overlapping onAppear load advanced contentVersion.
|
|
108
|
+
if (!next || (content && action !== "scopeLanded" && version !== contentVersion)) return undefined;
|
|
109
|
+
// A committed read projection supersedes older load results still carrying a skeleton.
|
|
110
|
+
if (action === "readChanged" && definition.readLifecycle) contentVersion++;
|
|
111
|
+
if (content) {
|
|
112
|
+
options.onContent?.(next);
|
|
113
|
+
const nextItems = options.items(next);
|
|
114
|
+
// This is an order-independent identity key, not display text. Default
|
|
115
|
+
// string ordering is deterministic on every worker engine, including QuickJS.
|
|
116
|
+
const nextItemsKey = JSON.stringify(nextItems.map(item => JSON.stringify([item.reference.kind, item.reference.id, item.commerceDisplayPrice]))
|
|
117
|
+
.sort());
|
|
118
|
+
items = nextItems;
|
|
119
|
+
const forcePriceRefresh = forcePriceRefreshActions.has(action);
|
|
120
|
+
if (forcePriceRefresh) settledViews.clear();
|
|
121
|
+
if (nextItemsKey !== loadedItemsKey || forcePriceRefresh) {
|
|
122
|
+
loadedItemsKey = nextItemsKey;
|
|
123
|
+
void commerce.loadPrices(items);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
// Checkout preserves prices published while it ran.
|
|
127
|
+
return project(concurrentPublish ? mergeConcurrent(state, next, committed()) : next);
|
|
128
|
+
};
|
|
129
|
+
const finished = () => {
|
|
130
|
+
activeActions--;
|
|
131
|
+
if (concurrentPublish) activeConcurrentPublishActions--;
|
|
132
|
+
const waiters = actionWaiters;
|
|
133
|
+
actionWaiters = [];
|
|
134
|
+
for (const resolve of waiters) resolve();
|
|
135
|
+
};
|
|
136
|
+
try {
|
|
137
|
+
const next = reduce(state, ...args);
|
|
138
|
+
// A cached read projection must commit before another onAppear can consume it.
|
|
139
|
+
// Other content actions retain their scheduling: shop filters and panels can
|
|
140
|
+
// change while a load is pending, and their existing completion order matters.
|
|
141
|
+
const synchronousReadProjection = action === "readChanged" && !!definition.readLifecycle;
|
|
142
|
+
if ((content && !synchronousReadProjection) || (next && typeof (next as Promise<S | undefined>).then === "function")) {
|
|
143
|
+
return (async () => {
|
|
144
|
+
try { return presentResult(await next); }
|
|
145
|
+
finally { finished(); }
|
|
146
|
+
})();
|
|
147
|
+
}
|
|
148
|
+
const result = presentResult(next as S | undefined);
|
|
149
|
+
finished();
|
|
150
|
+
return result;
|
|
151
|
+
} catch (error) {
|
|
152
|
+
finished();
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
}]));
|
|
156
|
+
const service = (options.register ?? defineService)(name, {
|
|
157
|
+
// The collection's shown page goes with the rows and chrome it copies: kept out of the restore with them.
|
|
158
|
+
...definition, notHydrated: [...(definition.notHydrated ?? []), ...options.transientKeys,
|
|
159
|
+
...((options.transientKeys as string[]).includes('collection') ? ['collectionShown' as keyof S & string] : [])],
|
|
160
|
+
// Prices land on their own clock, and a commit replaces the whole state — so a publish
|
|
161
|
+
// can carry a snapshot that an in-flight commit (a page that just landed, a tap) has
|
|
162
|
+
// since replaced. Project the state as it is now, and publish only when the prices
|
|
163
|
+
// actually change it: with no App Store mapping, or prices already shown, there is
|
|
164
|
+
// nothing to publish and nothing to overwrite.
|
|
165
|
+
actions: { ...actions, iapPublish: async () => {
|
|
166
|
+
// Checkout actions publish their busy phase while running. Every other action
|
|
167
|
+
// finishes before we take a projection, so it cannot erase a reducer's result.
|
|
168
|
+
for (;;) {
|
|
169
|
+
if (activeActions > activeConcurrentPublishActions) await new Promise<void>(resolve => actionWaiters.push(resolve));
|
|
170
|
+
await Promise.resolve();
|
|
171
|
+
const version = actionVersion;
|
|
172
|
+
await Promise.resolve();
|
|
173
|
+
if (activeActions <= activeConcurrentPublishActions && version === actionVersion) break;
|
|
174
|
+
}
|
|
175
|
+
const current = committed();
|
|
176
|
+
// The runtime commits an action's result just after this wrapper returns. If a
|
|
177
|
+
// scope action lands while prices are being projected, publishing this snapshot
|
|
178
|
+
// would put the older scope back on top. Drop it and retry against the commit.
|
|
179
|
+
const retainedPollVersion = uncommittedPollVersion;
|
|
180
|
+
const retainedPoll = uncommittedPollDirective;
|
|
181
|
+
const next: S & { _poll?: unknown } = project(current, retainedPoll);
|
|
182
|
+
await Promise.resolve();
|
|
183
|
+
if (committed() !== current) {
|
|
184
|
+
// Overlapping retries can race too: a projection with no new directive must
|
|
185
|
+
// not erase one another already retained after pollDirective() armed itself.
|
|
186
|
+
if (next._poll) {
|
|
187
|
+
uncommittedPollDirective = next._poll as ReturnType<IapCommerce["pollDirective"]>;
|
|
188
|
+
uncommittedPollVersion++;
|
|
189
|
+
}
|
|
190
|
+
queuePublish();
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
// Another concurrent projection may have retained a newer directive since this
|
|
194
|
+
// snapshot. Clear only the exact retained generation this successful commit used.
|
|
195
|
+
if (next._poll && retainedPollVersion === uncommittedPollVersion && retainedPoll === uncommittedPollDirective) {
|
|
196
|
+
uncommittedPollDirective = undefined;
|
|
197
|
+
uncommittedPollVersion++;
|
|
198
|
+
}
|
|
199
|
+
return !next._poll && JSON.stringify(next) === JSON.stringify(current) ? undefined : next;
|
|
200
|
+
}, iapPoll: async () => { await commerce.poll(); return undefined; },
|
|
201
|
+
iapRefresh: async () => { await commerce.loadPrices(items); return undefined; } },
|
|
202
|
+
});
|
|
203
|
+
committed = () => (service as unknown as { getState(): S }).getState();
|
|
204
|
+
resetUnhydratedKeysOnOlderRuntime(service, definition.state, options.transientKeys);
|
|
205
|
+
return service;
|
|
206
|
+
}) as unknown as typeof defineService;
|
|
207
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
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
|
+
retry: copyParam(`${prefix}.purchaseRetryText`, "Something went wrong. Try again."),
|
|
31
|
+
priceChanged: copyParam(`${prefix}.purchasePriceChangedText`, "The price changed. Check it and try again."),
|
|
32
|
+
support: copyParam(`${prefix}.purchaseSupportText`, "We couldn't finish this purchase. Contact support."),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The Restore purchases control (App Review 3.1.1) a screen binds. */
|
|
37
|
+
export interface IapRestoreFields {
|
|
38
|
+
restoreHidden: boolean;
|
|
39
|
+
restoreLabel: string;
|
|
40
|
+
restoreDisabled: boolean;
|
|
41
|
+
restoreMessage: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Keep these out of hydration: a restore's answer belongs to the run that got it. */
|
|
45
|
+
export const IAP_RESTORE_KEYS = ["restoreHidden", "restoreLabel", "restoreDisabled", "restoreMessage"] as const;
|
|
46
|
+
|
|
47
|
+
/** The control before the screen knows it sells through Apple. */
|
|
48
|
+
export const NO_IAP_RESTORE: IapRestoreFields = { restoreHidden: true, restoreLabel: "", restoreDisabled: false, restoreMessage: "" };
|
|
49
|
+
|
|
50
|
+
export interface IapRestoreControl {
|
|
51
|
+
/** `sellsThroughApple` is the screen's own signal: its item's App Store route, or Account's
|
|
52
|
+
* purchase readiness. */
|
|
53
|
+
fields(sellsThroughApple: boolean): IapRestoreFields;
|
|
54
|
+
/** Runs the shared `commerce.restore()`, repainting as it starts and when it answers. A tap while
|
|
55
|
+
* one runs is ignored. */
|
|
56
|
+
run(): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Copy from the screen's pack (`<prefix>.restorePurchasesCta`, …). The restore itself, and the access
|
|
60
|
+
* re-read after it, are the shared commerce's. */
|
|
61
|
+
export function createIapRestore(
|
|
62
|
+
commerce: Pick<IapCommerce, "restore">,
|
|
63
|
+
options: { prefix: string; repaint(): void; /** The session generation; defaults to the host's. */ generation?: () => number },
|
|
64
|
+
): IapRestoreControl {
|
|
65
|
+
const generation = options.generation ?? (() => hostSessionFromGlobal().current().generation);
|
|
66
|
+
let running = false;
|
|
67
|
+
let message = "";
|
|
68
|
+
let messageGeneration = -1;
|
|
69
|
+
|
|
70
|
+
function say(text: string, forGeneration: number): void {
|
|
71
|
+
message = text;
|
|
72
|
+
messageGeneration = forGeneration;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function run(): Promise<void> {
|
|
76
|
+
if (running) return;
|
|
77
|
+
running = true;
|
|
78
|
+
const startedFor = generation();
|
|
79
|
+
say(copyParam(`${options.prefix}.restoringText`, "Restoring…"), startedFor);
|
|
80
|
+
options.repaint();
|
|
81
|
+
// Stamped with the session the tap was for: an answer landing after a sign-out is never shown.
|
|
82
|
+
say(restoreMessage(await restored(commerce), options.prefix), startedFor);
|
|
83
|
+
running = false;
|
|
84
|
+
options.repaint();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
fields: (sellsThroughApple) => ({
|
|
89
|
+
restoreHidden: !sellsThroughApple,
|
|
90
|
+
restoreLabel: copyParam(`${options.prefix}.restorePurchasesCta`, "Restore purchases"),
|
|
91
|
+
restoreDisabled: running,
|
|
92
|
+
// The answer was for the person signed in when it ran; another session never inherits it.
|
|
93
|
+
restoreMessage: sellsThroughApple && messageGeneration === generation() ? message : "",
|
|
94
|
+
}),
|
|
95
|
+
run,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function restored(commerce: Pick<IapCommerce, "restore">): Promise<IapRestoreResult> {
|
|
100
|
+
return commerce.restore().catch(() => ({ status: "failed", code: "storeUnavailable" }) as const);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function restoreMessage(result: IapRestoreResult, prefix: string): string {
|
|
104
|
+
if (result.status === "needsSignIn") return copyParam(`${prefix}.restoreSignInText`, "Sign in to restore your purchases.");
|
|
105
|
+
if (result.status === "failed") return result.code === "sessionChanged" ? "" : copyParam(`${prefix}.restoreFailedText`, "Couldn't reach the App Store. Try again.");
|
|
106
|
+
// Every part that happened is said: a recovery never hides a refusal or a purchase still pending.
|
|
107
|
+
const parts = [
|
|
108
|
+
result.recovered === 1 ? copyParam(`${prefix}.restoredOneText`, "Restored 1 purchase.") : "",
|
|
109
|
+
result.recovered > 1 ? copyTemplate(`${prefix}.restoredManyText`, "Restored {count} purchases.", { count: result.recovered }) : "",
|
|
110
|
+
// Held unfinished because Wix refused it (another member's purchase, say).
|
|
111
|
+
result.refused > 0 ? copyParam(`${prefix}.restoreRefusedText`, "A purchase on this Apple ID couldn't be added to this account. Contact support.") : "",
|
|
112
|
+
result.pending > 0 ? copyParam(`${prefix}.restorePendingText`, "A purchase is still being confirmed. Try again in a moment.") : "",
|
|
113
|
+
].filter(Boolean);
|
|
114
|
+
return parts.length ? parts.join(" ") : copyParam(`${prefix}.restoreUpToDateText`, "Your purchases are up to date.");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** What `notHydrated` does, for a runtime that ignores the option (a binary older than it, still
|
|
118
|
+
* served new bundles): put the listed keys back to their declared values before any action runs,
|
|
119
|
+
* so a persisted price or an enabled purchase action never paints as this run's. */
|
|
120
|
+
export function resetUnhydratedKeysOnOlderRuntime<S extends object>(svc: { getState(): S }, declared: S, keys: readonly (keyof S & string)[]): void {
|
|
121
|
+
if ((globalThis as { himalaya?: { hydrationOptOut?: unknown } }).himalaya?.hydrationOptOut === true) return;
|
|
122
|
+
const booted = svc.getState();
|
|
123
|
+
if (!booted || typeof booted !== "object") return;
|
|
124
|
+
for (const key of keys) booted[key] = declared[key];
|
|
125
|
+
}
|
|
@@ -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,172 @@
|
|
|
1
|
+
// #2050 — the worker side of a followed live session, shared by the Owner and the
|
|
2
|
+
// Branded order flows.
|
|
3
|
+
//
|
|
4
|
+
// Shared deliberately rather than written twice. The two flows differ only in which
|
|
5
|
+
// record they follow and what they call it; everything that decides whether a
|
|
6
|
+
// background frame can ever reach the device — that a session ref is present, that
|
|
7
|
+
// it carries an expiry, that `pushUpdates` is on so iOS has a token to register — is
|
|
8
|
+
// identical, and two copies of it would drift into one flow silently losing
|
|
9
|
+
// background delivery while the other kept it.
|
|
10
|
+
//
|
|
11
|
+
// What is NOT here, on purpose: the account, the business, and the push token. The
|
|
12
|
+
// worker does not know them and must not choose them. The host reads its own signed-in
|
|
13
|
+
// scope at start and freezes it into the mapping, so a worker cannot scope a
|
|
14
|
+
// subscription to another tenant even by mistake.
|
|
15
|
+
|
|
16
|
+
import { start, end, type LiveActivityComponent } from "@himalaya/live-activity";
|
|
17
|
+
|
|
18
|
+
/** The fields a following worker adds to its own state. Flags are pre-negated
|
|
19
|
+
* because descriptors bind booleans through `hiddenWhen`, which takes one path. */
|
|
20
|
+
export interface LiveSessionFields {
|
|
21
|
+
/** Token for `end`. Empty when nothing is running. */
|
|
22
|
+
liveActivityId: string;
|
|
23
|
+
liveTracking: boolean;
|
|
24
|
+
notLiveTracking: boolean;
|
|
25
|
+
/** One honest line about the live surface — including "this device has none". */
|
|
26
|
+
liveNote: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const IDLE_LIVE_SESSION: LiveSessionFields = {
|
|
30
|
+
liveActivityId: "",
|
|
31
|
+
liveTracking: false,
|
|
32
|
+
notLiveTracking: true,
|
|
33
|
+
liveNote: "",
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
function node(id: string, type: string, props: Record<string, unknown>): LiveActivityComponent {
|
|
37
|
+
return { id, body: { package: "himalaya", type, props } };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The frozen widget-safe frame the live surface renders (family
|
|
42
|
+
* `ios_live_activity`): headline + one detail line. Only widget-safe components —
|
|
43
|
+
* the activity process has no worker, so a Card, Button or list would be dropped by
|
|
44
|
+
* the native renderer rather than rendered.
|
|
45
|
+
*
|
|
46
|
+
* This is the FIRST frame only. Every later frame arrives from the serve plane with
|
|
47
|
+
* its own content, which is the entire point of the subscription: the worker is gone
|
|
48
|
+
* by then.
|
|
49
|
+
*/
|
|
50
|
+
export function liveSessionFrame(headline: string, detail: string): LiveActivityComponent {
|
|
51
|
+
return node("live_root", "VStack", {
|
|
52
|
+
spacing: 6,
|
|
53
|
+
children: [
|
|
54
|
+
node("live_headline", "Text", { text: headline, style: "bodyEmphasis" }),
|
|
55
|
+
node("live_detail", "Text", { text: detail, style: "caption" }),
|
|
56
|
+
],
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface BeginLiveSessionOptions {
|
|
61
|
+
/** Groups related activities (iOS attributes type / Android channel tag). */
|
|
62
|
+
activityType: string;
|
|
63
|
+
entityType: "order" | "booking" | "session";
|
|
64
|
+
/** The exact record id. Scoped by the host's account/business, never global. */
|
|
65
|
+
entityId: string;
|
|
66
|
+
headline: string;
|
|
67
|
+
detail: string;
|
|
68
|
+
/** Exact record route, so the surface opens the record it is about. Required by
|
|
69
|
+
* the subscription registry — a subscription that cannot name its record cannot
|
|
70
|
+
* satisfy "deep-link into the exact record after process death". */
|
|
71
|
+
deepLink: string;
|
|
72
|
+
/** How long the session may live, in seconds from now. */
|
|
73
|
+
ttlSeconds: number;
|
|
74
|
+
/** Re-entry with the activity token (or "" when the device has no live surface). */
|
|
75
|
+
onStarted: (activityId: string) => void;
|
|
76
|
+
/** Copy for the two terminal notes, so each flow speaks its own language. */
|
|
77
|
+
startingNote: string;
|
|
78
|
+
unavailableNote: string;
|
|
79
|
+
now?: () => number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Which start attempt is still wanted.
|
|
84
|
+
*
|
|
85
|
+
* `beginLiveSession` returns `liveTracking: true` with an EMPTY `liveActivityId`, so
|
|
86
|
+
* the row offers "Stop following" while `start` is still in flight. Stopping in that
|
|
87
|
+
* window used to be silently undone: `stopLiveSession` had no id to end, and the
|
|
88
|
+
* pending `.then` then called `onStarted` and flipped the row back to following —
|
|
89
|
+
* over a surface the OS had just created and the revoked subscription would never
|
|
90
|
+
* address again. A tap the user made is not a tap the app may discard, so the stop
|
|
91
|
+
* invalidates the start instead. (#2237 review)
|
|
92
|
+
*/
|
|
93
|
+
let startGeneration = 0;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Begin following a record. Returns the "starting" fields immediately and re-enters
|
|
97
|
+
* through `onStarted` — `start` is not awaited so the button flips at once, the same
|
|
98
|
+
* pattern the demo live-activity worker uses and for the same reason: T5 is
|
|
99
|
+
* request/response, so an awaited network round trip would freeze the row.
|
|
100
|
+
*/
|
|
101
|
+
export function beginLiveSession(o: BeginLiveSessionOptions): LiveSessionFields {
|
|
102
|
+
const nowSeconds = Math.floor((o.now?.() ?? Date.now()) / 1000);
|
|
103
|
+
const generation = ++startGeneration;
|
|
104
|
+
start({
|
|
105
|
+
activityType: o.activityType,
|
|
106
|
+
content: liveSessionFrame(o.headline, o.detail),
|
|
107
|
+
title: o.headline,
|
|
108
|
+
deepLink: o.deepLink,
|
|
109
|
+
// Both are load-bearing on iOS: `session` records the mapping, `pushUpdates`
|
|
110
|
+
// asks ActivityKit for the token the host registers. With only the first, the
|
|
111
|
+
// device would hold a mapping nothing can ever address.
|
|
112
|
+
pushUpdates: true,
|
|
113
|
+
// Android promotion: a user-followed, bounded, time-sensitive activity is
|
|
114
|
+
// exactly what it is for. The system may still keep it an ordinary notification.
|
|
115
|
+
promoted: true,
|
|
116
|
+
// The SAME TTL the registry session gets, handed to the NATIVE surface too.
|
|
117
|
+
// Omitting it did not mean "use a sensible default": the SDK sends 0,
|
|
118
|
+
// `LiveUpdatePolicy.DEFAULT_TTL_MS` is 0, `duration(0)` returns 0, and the
|
|
119
|
+
// capability then stores `Long.MAX_VALUE` and calls `setTimeoutAfter(0)` — so
|
|
120
|
+
// an Android Live Update with no terminal push and no revocation stayed on
|
|
121
|
+
// the shade forever, while the declared follow TTL said 12 or 24 hours.
|
|
122
|
+
// Android clamps to its own MAX_TTL_MS (8h), which is its bound to enforce.
|
|
123
|
+
// (#2237 review)
|
|
124
|
+
staleAfterMs: o.ttlSeconds * 1000,
|
|
125
|
+
session: {
|
|
126
|
+
entityType: o.entityType,
|
|
127
|
+
entityId: o.entityId,
|
|
128
|
+
expiresAt: nowSeconds + o.ttlSeconds,
|
|
129
|
+
},
|
|
130
|
+
})
|
|
131
|
+
.then((r) => {
|
|
132
|
+
if (generation !== startGeneration) {
|
|
133
|
+
// Unfollowed while this was starting. The surface exists NOW and the
|
|
134
|
+
// unfollow could not end it — there was no id yet — so end it here.
|
|
135
|
+
// Skipping this is what leaves an unaddressable live surface on the
|
|
136
|
+
// device after the user has already stopped.
|
|
137
|
+
if (r.activityId) end({ activityId: r.activityId, dismissAfterMs: 0 });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
o.onStarted(r.activityId);
|
|
141
|
+
})
|
|
142
|
+
.catch(() => {
|
|
143
|
+
// A failed start has nothing to clean up; it must still not report itself
|
|
144
|
+
// onto a row the user has moved on from.
|
|
145
|
+
if (generation === startGeneration) o.onStarted("");
|
|
146
|
+
});
|
|
147
|
+
return { liveActivityId: "", liveTracking: true, notLiveTracking: false, liveNote: o.startingNote };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Resolve the deferred start. An empty id means the device has no live surface
|
|
151
|
+
* (web, iOS < 16.2, activities or notifications disabled) — reported, not hidden. */
|
|
152
|
+
export function liveSessionStarted(
|
|
153
|
+
activityId: string,
|
|
154
|
+
followingNote: string,
|
|
155
|
+
unavailableNote: string,
|
|
156
|
+
): LiveSessionFields {
|
|
157
|
+
const id = (activityId ?? "").trim();
|
|
158
|
+
if (!id) return { ...IDLE_LIVE_SESSION, liveNote: unavailableNote };
|
|
159
|
+
return { liveActivityId: id, liveTracking: true, notLiveTracking: false, liveNote: followingNote };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Stop following. Ends the OS surface; the host's own cleanup drops the server
|
|
164
|
+
* subscription, so the server cannot keep pushing to a surface the user dismissed.
|
|
165
|
+
*/
|
|
166
|
+
export function stopLiveSession(activityId: string, stoppedNote: string): LiveSessionFields {
|
|
167
|
+
// Cancels a start still in flight. Unconditional, because the case this exists
|
|
168
|
+
// for is exactly the one where `activityId` is still empty.
|
|
169
|
+
startGeneration++;
|
|
170
|
+
if (activityId) end({ activityId, dismissAfterMs: 0 });
|
|
171
|
+
return { ...IDLE_LIVE_SESSION, liveNote: stoppedNote };
|
|
172
|
+
}
|
|
@@ -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
|
+
}
|