@wix/himalaya-cli 0.1943.0 → 0.1945.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 (273) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +5 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/wix-sdk/ecom/src/extensions.d.ts +27 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +6 -0
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-ecom.mjs +16 -0
  5. package/dist/cli.mjs +1186 -644
  6. package/fixtures/wix-canned.json +6 -0
  7. package/guides/himi-json-output.md +8 -6
  8. package/guides/one-app-section-mappings.md +2 -2
  9. package/guides/one-app-to-himi-app.md +13 -4
  10. package/guides/release-notes.md +8 -0
  11. package/guides/sdk-reference.json +56 -1
  12. package/guides/splash-screens.md +14 -2
  13. package/package.json +2 -2
  14. package/templates/bare-fashion/dev/index.ts +3 -1
  15. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-product-card.ts +5 -4
  16. package/templates/bare-fashion/tier5-src/_shared/collection-service.ts +35 -15
  17. package/templates/bare-fashion/tier5-src/_shared/himi-store-saved.ts +275 -13
  18. package/templates/bare-fashion/tier5-src/himi-bare-fashion-cart/index.ts +19 -12
  19. package/templates/bare-fashion/tier5-src/himi-bare-fashion-collection/index.ts +9 -4
  20. package/templates/bare-fashion/tier5-src/himi-bare-fashion-home/index.ts +10 -4
  21. package/templates/bare-fashion/tier5-src/himi-bare-fashion-product/index.ts +17 -8
  22. package/templates/bare-fashion/tier5-src/himi-bare-fashion-products/index.ts +8 -4
  23. package/templates/bare-fashion/tier5-src/himi-bare-fashion-saved/index.ts +31 -12
  24. package/templates/bare-fashion/tier5-src/himi-bare-fashion-search/index.ts +8 -4
  25. package/templates/beauty-salon/tier5-src/_shared/collection-service.ts +35 -15
  26. package/templates/beauty-salon/tier5-src/_shared/himi-store-facets.ts +4 -4
  27. package/templates/beauty-salon/tier5-src/_shared/himi-store-saved.ts +275 -13
  28. package/templates/beauty-salon/tier5-src/himi-branded-lite-cart/index.ts +13 -7
  29. package/templates/beauty-salon/tier5-src/himi-branded-lite-category/index.ts +6 -1
  30. package/templates/beauty-salon/tier5-src/himi-branded-lite-home/index.ts +6 -5
  31. package/templates/beauty-salon/tier5-src/himi-branded-lite-shop/index.ts +9 -3
  32. package/templates/beauty-salon/tier5-src/himi-store-product/index.ts +7 -5
  33. package/templates/beauty-salon/tier5-src/himi-store-saved/index.ts +31 -12
  34. package/templates/beauty-salon-owner/tier5-src/_shared/collection-service.ts +35 -15
  35. package/templates/branded-lite/recipes/wishlist-grid.json +1 -1
  36. package/templates/branded-lite/tier5-src/_shared/collection-service.ts +42 -19
  37. package/templates/branded-lite/tier5-src/_shared/himi-store-facets.ts +4 -4
  38. package/templates/branded-lite/tier5-src/_shared/himi-store-saved.ts +275 -13
  39. package/templates/branded-lite/tier5-src/_shared/saved-products-section.ts +14 -8
  40. package/templates/branded-lite/tier5-src/himi-branded-lite-cart/index.ts +13 -7
  41. package/templates/branded-lite/tier5-src/himi-branded-lite-category/index.ts +6 -1
  42. package/templates/branded-lite/tier5-src/himi-branded-lite-home/index.ts +6 -5
  43. package/templates/branded-lite/tier5-src/himi-branded-lite-shop/index.ts +9 -3
  44. package/templates/branded-lite/tier5-src/himi-store-product/index.ts +32 -15
  45. package/templates/branded-lite/tier5-src/himi-store-saved/index.ts +31 -12
  46. package/templates/brandy/tier5-src/_shared/collection-service.ts +42 -19
  47. package/templates/brandy/tier5-src/_shared/himi-store-saved.ts +275 -13
  48. package/templates/brandy/tier5-src/himi-branded-lite-cart/index.ts +13 -7
  49. package/templates/community-club/l10n/ar.json +5 -0
  50. package/templates/community-club/l10n/cs.json +5 -0
  51. package/templates/community-club/l10n/da.json +5 -0
  52. package/templates/community-club/l10n/de.json +5 -0
  53. package/templates/community-club/l10n/el.json +5 -0
  54. package/templates/community-club/l10n/es.json +5 -0
  55. package/templates/community-club/l10n/fi.json +5 -0
  56. package/templates/community-club/l10n/fr.json +5 -0
  57. package/templates/community-club/l10n/he.json +4 -0
  58. package/templates/community-club/l10n/hu.json +5 -0
  59. package/templates/community-club/l10n/id.json +5 -0
  60. package/templates/community-club/l10n/it.json +5 -0
  61. package/templates/community-club/l10n/ja.json +5 -0
  62. package/templates/community-club/l10n/ko.json +5 -0
  63. package/templates/community-club/l10n/lt.json +5 -0
  64. package/templates/community-club/l10n/nl.json +5 -0
  65. package/templates/community-club/l10n/no.json +5 -0
  66. package/templates/community-club/l10n/pl.json +5 -0
  67. package/templates/community-club/l10n/pt.json +5 -0
  68. package/templates/community-club/l10n/ru.json +5 -0
  69. package/templates/community-club/l10n/sv.json +5 -0
  70. package/templates/community-club/l10n/th.json +5 -0
  71. package/templates/community-club/l10n/tr.json +5 -0
  72. package/templates/community-club/l10n/uk.json +5 -0
  73. package/templates/community-club/l10n/vi.json +5 -0
  74. package/templates/community-club/l10n/zh.json +5 -0
  75. package/templates/community-club/tier5-src/_shared/collection-service.ts +35 -15
  76. package/templates/community-club/tier5-src/_shared/himi-store-saved.ts +275 -13
  77. package/templates/community-club/tier5-src/himi-branded-lite-home/index.ts +6 -5
  78. package/templates/community-club-owner/tier5-src/_shared/collection-service.ts +35 -15
  79. package/templates/conference/tier5-src/_shared/collection-service.ts +35 -15
  80. package/templates/events-meetups/l10n/ar.json +5 -0
  81. package/templates/events-meetups/l10n/cs.json +5 -0
  82. package/templates/events-meetups/l10n/da.json +5 -0
  83. package/templates/events-meetups/l10n/de.json +5 -0
  84. package/templates/events-meetups/l10n/el.json +5 -0
  85. package/templates/events-meetups/l10n/es.json +5 -0
  86. package/templates/events-meetups/l10n/fi.json +5 -0
  87. package/templates/events-meetups/l10n/fr.json +5 -0
  88. package/templates/events-meetups/l10n/he.json +4 -0
  89. package/templates/events-meetups/l10n/hu.json +5 -0
  90. package/templates/events-meetups/l10n/id.json +5 -0
  91. package/templates/events-meetups/l10n/it.json +5 -0
  92. package/templates/events-meetups/l10n/ja.json +5 -0
  93. package/templates/events-meetups/l10n/ko.json +5 -0
  94. package/templates/events-meetups/l10n/lt.json +5 -0
  95. package/templates/events-meetups/l10n/nl.json +5 -0
  96. package/templates/events-meetups/l10n/no.json +5 -0
  97. package/templates/events-meetups/l10n/pl.json +5 -0
  98. package/templates/events-meetups/l10n/pt.json +5 -0
  99. package/templates/events-meetups/l10n/ru.json +5 -0
  100. package/templates/events-meetups/l10n/sv.json +5 -0
  101. package/templates/events-meetups/l10n/th.json +5 -0
  102. package/templates/events-meetups/l10n/tr.json +5 -0
  103. package/templates/events-meetups/l10n/uk.json +5 -0
  104. package/templates/events-meetups/l10n/vi.json +5 -0
  105. package/templates/events-meetups/l10n/zh.json +5 -0
  106. package/templates/events-meetups/tier5-src/_shared/collection-service.ts +35 -15
  107. package/templates/events-meetups/tier5-src/_shared/himi-store-saved.ts +275 -13
  108. package/templates/events-meetups/tier5-src/himi-branded-lite-home/index.ts +6 -5
  109. package/templates/events-meetups-owner/tier5-src/_shared/collection-service.ts +35 -15
  110. package/templates/fitness-gym/tier5-src/_shared/collection-service.ts +35 -15
  111. package/templates/gym-fitness/tier5-src/_shared/collection-service.ts +35 -15
  112. package/templates/gym-fitness/tier5-src/_shared/himi-store-facets.ts +4 -4
  113. package/templates/gym-fitness/tier5-src/_shared/himi-store-saved.ts +275 -13
  114. package/templates/gym-fitness/tier5-src/himi-branded-lite-cart/index.ts +13 -7
  115. package/templates/gym-fitness/tier5-src/himi-branded-lite-category/index.ts +6 -1
  116. package/templates/gym-fitness/tier5-src/himi-branded-lite-home/index.ts +6 -5
  117. package/templates/gym-fitness/tier5-src/himi-branded-lite-shop/index.ts +9 -3
  118. package/templates/gym-fitness/tier5-src/himi-store-product/index.ts +7 -5
  119. package/templates/gym-fitness/tier5-src/himi-store-saved/index.ts +31 -12
  120. package/templates/gym-fitness-owner/tier5-src/_shared/collection-service.ts +35 -15
  121. package/templates/medical-services/tier5-src/_shared/collection-service.ts +35 -15
  122. package/templates/nonprofit-cause/l10n/ar.json +5 -0
  123. package/templates/nonprofit-cause/l10n/cs.json +5 -0
  124. package/templates/nonprofit-cause/l10n/da.json +5 -0
  125. package/templates/nonprofit-cause/l10n/de.json +5 -0
  126. package/templates/nonprofit-cause/l10n/el.json +5 -0
  127. package/templates/nonprofit-cause/l10n/es.json +5 -0
  128. package/templates/nonprofit-cause/l10n/fi.json +5 -0
  129. package/templates/nonprofit-cause/l10n/fr.json +5 -0
  130. package/templates/nonprofit-cause/l10n/he.json +4 -0
  131. package/templates/nonprofit-cause/l10n/hu.json +5 -0
  132. package/templates/nonprofit-cause/l10n/id.json +5 -0
  133. package/templates/nonprofit-cause/l10n/it.json +5 -0
  134. package/templates/nonprofit-cause/l10n/ja.json +5 -0
  135. package/templates/nonprofit-cause/l10n/ko.json +5 -0
  136. package/templates/nonprofit-cause/l10n/lt.json +5 -0
  137. package/templates/nonprofit-cause/l10n/nl.json +5 -0
  138. package/templates/nonprofit-cause/l10n/no.json +5 -0
  139. package/templates/nonprofit-cause/l10n/pl.json +5 -0
  140. package/templates/nonprofit-cause/l10n/pt.json +5 -0
  141. package/templates/nonprofit-cause/l10n/ru.json +5 -0
  142. package/templates/nonprofit-cause/l10n/sv.json +5 -0
  143. package/templates/nonprofit-cause/l10n/th.json +5 -0
  144. package/templates/nonprofit-cause/l10n/tr.json +5 -0
  145. package/templates/nonprofit-cause/l10n/uk.json +5 -0
  146. package/templates/nonprofit-cause/l10n/vi.json +5 -0
  147. package/templates/nonprofit-cause/l10n/zh.json +5 -0
  148. package/templates/nonprofit-cause/tier5-src/_shared/collection-service.ts +35 -15
  149. package/templates/nonprofit-cause/tier5-src/_shared/himi-store-saved.ts +275 -13
  150. package/templates/nonprofit-cause/tier5-src/himi-branded-lite-home/index.ts +6 -5
  151. package/templates/nonprofit-cause-owner/tier5-src/_shared/collection-service.ts +35 -15
  152. package/templates/owner-lite/tier5-src/_shared/collection-service.ts +35 -15
  153. package/templates/personal-fitness-trainer/tier5-src/_shared/collection-service.ts +35 -15
  154. package/templates/podcast-creator/l10n/ar.json +5 -0
  155. package/templates/podcast-creator/l10n/cs.json +5 -0
  156. package/templates/podcast-creator/l10n/da.json +5 -0
  157. package/templates/podcast-creator/l10n/de.json +5 -0
  158. package/templates/podcast-creator/l10n/el.json +5 -0
  159. package/templates/podcast-creator/l10n/es.json +5 -0
  160. package/templates/podcast-creator/l10n/fi.json +5 -0
  161. package/templates/podcast-creator/l10n/fr.json +5 -0
  162. package/templates/podcast-creator/l10n/he.json +4 -0
  163. package/templates/podcast-creator/l10n/hu.json +5 -0
  164. package/templates/podcast-creator/l10n/id.json +5 -0
  165. package/templates/podcast-creator/l10n/it.json +5 -0
  166. package/templates/podcast-creator/l10n/ja.json +5 -0
  167. package/templates/podcast-creator/l10n/ko.json +5 -0
  168. package/templates/podcast-creator/l10n/lt.json +5 -0
  169. package/templates/podcast-creator/l10n/nl.json +5 -0
  170. package/templates/podcast-creator/l10n/no.json +5 -0
  171. package/templates/podcast-creator/l10n/pl.json +5 -0
  172. package/templates/podcast-creator/l10n/pt.json +5 -0
  173. package/templates/podcast-creator/l10n/ru.json +5 -0
  174. package/templates/podcast-creator/l10n/sv.json +5 -0
  175. package/templates/podcast-creator/l10n/th.json +5 -0
  176. package/templates/podcast-creator/l10n/tr.json +5 -0
  177. package/templates/podcast-creator/l10n/uk.json +5 -0
  178. package/templates/podcast-creator/l10n/vi.json +5 -0
  179. package/templates/podcast-creator/l10n/zh.json +5 -0
  180. package/templates/podcast-creator/tier5-src/_shared/collection-service.ts +35 -15
  181. package/templates/podcast-creator/tier5-src/_shared/himi-store-saved.ts +275 -13
  182. package/templates/podcast-creator/tier5-src/himi-branded-lite-home/index.ts +6 -5
  183. package/templates/podcast-creator-owner/tier5-src/_shared/collection-service.ts +35 -15
  184. package/templates/portfolio-creative/tier5-src/_shared/collection-service.ts +35 -15
  185. package/templates/portfolio-creative/tier5-src/_shared/himi-store-facets.ts +4 -4
  186. package/templates/portfolio-creative/tier5-src/_shared/himi-store-saved.ts +275 -13
  187. package/templates/portfolio-creative/tier5-src/himi-branded-lite-cart/index.ts +13 -7
  188. package/templates/portfolio-creative/tier5-src/himi-branded-lite-category/index.ts +6 -1
  189. package/templates/portfolio-creative/tier5-src/himi-branded-lite-home/index.ts +6 -5
  190. package/templates/portfolio-creative/tier5-src/himi-branded-lite-shop/index.ts +9 -3
  191. package/templates/portfolio-creative/tier5-src/himi-store-product/index.ts +7 -5
  192. package/templates/portfolio-creative/tier5-src/himi-store-saved/index.ts +31 -12
  193. package/templates/portfolio-creative-owner/tier5-src/_shared/collection-service.ts +35 -15
  194. package/templates/professional-services/tier5-src/_shared/collection-service.ts +35 -15
  195. package/templates/restaurant/l10n/ar.json +5 -0
  196. package/templates/restaurant/l10n/cs.json +5 -0
  197. package/templates/restaurant/l10n/da.json +5 -0
  198. package/templates/restaurant/l10n/de.json +5 -0
  199. package/templates/restaurant/l10n/el.json +5 -0
  200. package/templates/restaurant/l10n/es.json +5 -0
  201. package/templates/restaurant/l10n/fi.json +5 -0
  202. package/templates/restaurant/l10n/fr.json +5 -0
  203. package/templates/restaurant/l10n/he.json +4 -0
  204. package/templates/restaurant/l10n/hu.json +5 -0
  205. package/templates/restaurant/l10n/id.json +5 -0
  206. package/templates/restaurant/l10n/it.json +5 -0
  207. package/templates/restaurant/l10n/ja.json +5 -0
  208. package/templates/restaurant/l10n/ko.json +5 -0
  209. package/templates/restaurant/l10n/lt.json +5 -0
  210. package/templates/restaurant/l10n/nl.json +5 -0
  211. package/templates/restaurant/l10n/no.json +5 -0
  212. package/templates/restaurant/l10n/pl.json +5 -0
  213. package/templates/restaurant/l10n/pt.json +5 -0
  214. package/templates/restaurant/l10n/ru.json +5 -0
  215. package/templates/restaurant/l10n/sv.json +5 -0
  216. package/templates/restaurant/l10n/th.json +5 -0
  217. package/templates/restaurant/l10n/tr.json +5 -0
  218. package/templates/restaurant/l10n/uk.json +5 -0
  219. package/templates/restaurant/l10n/vi.json +5 -0
  220. package/templates/restaurant/l10n/zh.json +5 -0
  221. package/templates/restaurant/tier5-src/_shared/collection-service.ts +35 -15
  222. package/templates/restaurant/tier5-src/_shared/himi-store-saved.ts +275 -13
  223. package/templates/restaurant/tier5-src/himi-branded-lite-home/index.ts +6 -5
  224. package/templates/restaurant-owner/tier5-src/_shared/collection-service.ts +35 -15
  225. package/templates/retail-store/tier5-src/_shared/collection-service.ts +42 -19
  226. package/templates/retail-store/tier5-src/_shared/himi-store-facets.ts +4 -4
  227. package/templates/retail-store/tier5-src/_shared/himi-store-saved.ts +275 -13
  228. package/templates/retail-store/tier5-src/himi-branded-lite-cart/index.ts +13 -7
  229. package/templates/retail-store/tier5-src/himi-branded-lite-category/index.ts +6 -1
  230. package/templates/retail-store/tier5-src/himi-branded-lite-home/index.ts +6 -5
  231. package/templates/retail-store/tier5-src/himi-branded-lite-shop/index.ts +9 -3
  232. package/templates/retail-store/tier5-src/himi-store-product/index.ts +32 -15
  233. package/templates/retail-store/tier5-src/himi-store-saved/index.ts +31 -12
  234. package/templates/retail-store-owner/tier5-src/_shared/collection-service.ts +35 -15
  235. package/templates/salon-spa/tier5-src/_shared/collection-service.ts +35 -15
  236. package/templates/wholesale-store/dev/index.ts +2 -2
  237. package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +42 -19
  238. package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +7 -3
  239. package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +275 -13
  240. package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +13 -7
  241. package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +32 -15
  242. package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +31 -12
  243. package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +19 -8
  244. package/templates/yoga-studio/l10n/ar.json +5 -0
  245. package/templates/yoga-studio/l10n/cs.json +5 -0
  246. package/templates/yoga-studio/l10n/da.json +5 -0
  247. package/templates/yoga-studio/l10n/de.json +5 -0
  248. package/templates/yoga-studio/l10n/el.json +5 -0
  249. package/templates/yoga-studio/l10n/es.json +5 -0
  250. package/templates/yoga-studio/l10n/fi.json +5 -0
  251. package/templates/yoga-studio/l10n/fr.json +5 -0
  252. package/templates/yoga-studio/l10n/he.json +4 -0
  253. package/templates/yoga-studio/l10n/hu.json +5 -0
  254. package/templates/yoga-studio/l10n/id.json +5 -0
  255. package/templates/yoga-studio/l10n/it.json +5 -0
  256. package/templates/yoga-studio/l10n/ja.json +5 -0
  257. package/templates/yoga-studio/l10n/ko.json +5 -0
  258. package/templates/yoga-studio/l10n/lt.json +5 -0
  259. package/templates/yoga-studio/l10n/nl.json +5 -0
  260. package/templates/yoga-studio/l10n/no.json +5 -0
  261. package/templates/yoga-studio/l10n/pl.json +5 -0
  262. package/templates/yoga-studio/l10n/pt.json +5 -0
  263. package/templates/yoga-studio/l10n/ru.json +5 -0
  264. package/templates/yoga-studio/l10n/sv.json +5 -0
  265. package/templates/yoga-studio/l10n/th.json +5 -0
  266. package/templates/yoga-studio/l10n/tr.json +5 -0
  267. package/templates/yoga-studio/l10n/uk.json +5 -0
  268. package/templates/yoga-studio/l10n/vi.json +5 -0
  269. package/templates/yoga-studio/l10n/zh.json +5 -0
  270. package/templates/yoga-studio/tier5-src/_shared/collection-service.ts +35 -15
  271. package/templates/yoga-studio/tier5-src/_shared/himi-store-saved.ts +275 -13
  272. package/templates/yoga-studio/tier5-src/himi-branded-lite-home/index.ts +6 -5
  273. package/templates/yoga-studio-owner/tier5-src/_shared/collection-service.ts +35 -15
@@ -15,7 +15,10 @@ type MemberAvatarFactory = (changed: () => void) => {
15
15
 
16
16
  export interface CollectionSaving {
17
17
  read(): string[];
18
- write(ids: string[], rows: Record<string, unknown>[]): void;
18
+ /** May settle later (an account write); a rejection restores the selection and says so. */
19
+ write(ids: string[], rows: Record<string, unknown>[]): void | Promise<void>;
20
+ /** Re-read the saved ids `read` answers (an account list), before a load or refresh reads them. */
21
+ refresh?(): Promise<void>;
19
22
  }
20
23
  type State = Record<string, unknown>;
21
24
  interface BackendCollection {
@@ -263,19 +266,33 @@ export function decorateCollection(name: string, def: { state: State; actions?:
263
266
  const criteriaBefore = criteriaKey();
264
267
  const before = [...prefs.savedIds], undoBefore = lastUndo;
265
268
  update(arg, s);
269
+ const failed = () => {
270
+ prefs.savedIds = before; lastUndo = undoBefore;
271
+ saveMessage = copyParam('collection.saveError', 'Could not save this change. Try again.');
272
+ };
273
+ const finish = (settledLater: boolean) => {
274
+ persisted.write(prefs);
275
+ if (backend && config.backendQuery && criteriaBefore !== criteriaKey()) return backend.controller.query(criteria()).then(() => undefined);
276
+ // A write that settled later lands on the rows as they are now, not as they were when it began.
277
+ return derive(settledLater && backend ? backend.apply(s, backend.controller.getState()) : s);
278
+ };
266
279
  if (saving && JSON.stringify(before) !== JSON.stringify(prefs.savedIds)) {
280
+ let written: void | Promise<void>;
267
281
  try {
268
- saving.write(prefs.savedIds, Array.isArray(s[config.rows]) ? s[config.rows] as CollectionRow[] : []);
269
- saveMessage = '';
282
+ written = saving.write(prefs.savedIds, Array.isArray(s[config.rows]) ? s[config.rows] as CollectionRow[] : []);
270
283
  } catch {
271
- prefs.savedIds = before; lastUndo = undoBefore;
272
- saveMessage = copyParam('collection.saveError', 'Could not save this change. Try again.');
284
+ failed();
285
+ return finish(false);
286
+ }
287
+ if (written && typeof written.then === 'function') {
288
+ return written.then(() => { saveMessage = ''; return finish(true); }, () => { failed(); return finish(true); });
273
289
  }
290
+ saveMessage = '';
274
291
  }
275
- persisted.write(prefs);
276
- if (backend && config.backendQuery && criteriaBefore !== criteriaKey()) return backend.controller.query(criteria()).then(() => undefined);
277
- return derive(s);
292
+ return finish(false);
278
293
  };
294
+ /** Runs `then` once the saved ids are re-read (an account list); at once, in the same turn, when there is nothing to re-read. */
295
+ const afterSavingRefresh = (then: () => Promise<undefined>): Promise<undefined> => saving?.refresh ? saving.refresh().catch(() => undefined).then(then) : then();
279
296
  /** Filter and sort in ONE criteria change, so a tab that sets both runs one query, not two. */
280
297
  const setCriteria = (arg: unknown): void => {
281
298
  const input = object(arg);
@@ -329,15 +346,18 @@ export function decorateCollection(name: string, def: { state: State; actions?:
329
346
  if (backend) {
330
347
  actions.collectionDataChanged = s => derive(backend.apply(s, backend.controller.getState()));
331
348
  actions.load = (_s, arg) => {
332
- stashCopy(arg); syncSaved(); applyNavigationCriteria(arg, _s);
333
- const reset = backend.onLoad?.(arg);
334
- if (reset) { setCriteria(reset); persisted.write(prefs); }
335
- // A load of what the screen already shows is the screen coming back: it revalidates behind its rows.
336
- return backend.controller.query(criteria(), backend.restorePagesOnLoad, true).then(() => undefined);
349
+ stashCopy(arg);
350
+ return afterSavingRefresh(() => {
351
+ syncSaved(); applyNavigationCriteria(arg, _s);
352
+ const reset = backend.onLoad?.(arg);
353
+ if (reset) { setCriteria(reset); persisted.write(prefs); }
354
+ // A load of what the screen already shows is the screen coming back: it revalidates behind its rows.
355
+ return backend.controller.query(criteria(), backend.restorePagesOnLoad, true).then(() => undefined);
356
+ });
337
357
  };
338
358
  actions.refresh = (_s, arg) => {
339
- stashCopy(arg); syncSaved();
340
- return backend.controller.query(criteria()).then(() => undefined);
359
+ stashCopy(arg);
360
+ return afterSavingRefresh(() => { syncSaved(); return backend.controller.query(criteria()).then(() => undefined); });
341
361
  };
342
362
  actions.loadMore = () => backend.controller.loadMore().then(() => undefined);
343
363
  actions.retry = actions.collectionRetry = () => backend.controller.retry().then(() => undefined);
@@ -15,7 +15,10 @@ type MemberAvatarFactory = (changed: () => void) => {
15
15
 
16
16
  export interface CollectionSaving {
17
17
  read(): string[];
18
- write(ids: string[], rows: Record<string, unknown>[]): void;
18
+ /** May settle later (an account write); a rejection restores the selection and says so. */
19
+ write(ids: string[], rows: Record<string, unknown>[]): void | Promise<void>;
20
+ /** Re-read the saved ids `read` answers (an account list), before a load or refresh reads them. */
21
+ refresh?(): Promise<void>;
19
22
  }
20
23
  type State = Record<string, unknown>;
21
24
  interface BackendCollection {
@@ -263,19 +266,33 @@ export function decorateCollection(name: string, def: { state: State; actions?:
263
266
  const criteriaBefore = criteriaKey();
264
267
  const before = [...prefs.savedIds], undoBefore = lastUndo;
265
268
  update(arg, s);
269
+ const failed = () => {
270
+ prefs.savedIds = before; lastUndo = undoBefore;
271
+ saveMessage = copyParam('collection.saveError', 'Could not save this change. Try again.');
272
+ };
273
+ const finish = (settledLater: boolean) => {
274
+ persisted.write(prefs);
275
+ if (backend && config.backendQuery && criteriaBefore !== criteriaKey()) return backend.controller.query(criteria()).then(() => undefined);
276
+ // A write that settled later lands on the rows as they are now, not as they were when it began.
277
+ return derive(settledLater && backend ? backend.apply(s, backend.controller.getState()) : s);
278
+ };
266
279
  if (saving && JSON.stringify(before) !== JSON.stringify(prefs.savedIds)) {
280
+ let written: void | Promise<void>;
267
281
  try {
268
- saving.write(prefs.savedIds, Array.isArray(s[config.rows]) ? s[config.rows] as CollectionRow[] : []);
269
- saveMessage = '';
282
+ written = saving.write(prefs.savedIds, Array.isArray(s[config.rows]) ? s[config.rows] as CollectionRow[] : []);
270
283
  } catch {
271
- prefs.savedIds = before; lastUndo = undoBefore;
272
- saveMessage = copyParam('collection.saveError', 'Could not save this change. Try again.');
284
+ failed();
285
+ return finish(false);
286
+ }
287
+ if (written && typeof written.then === 'function') {
288
+ return written.then(() => { saveMessage = ''; return finish(true); }, () => { failed(); return finish(true); });
273
289
  }
290
+ saveMessage = '';
274
291
  }
275
- persisted.write(prefs);
276
- if (backend && config.backendQuery && criteriaBefore !== criteriaKey()) return backend.controller.query(criteria()).then(() => undefined);
277
- return derive(s);
292
+ return finish(false);
278
293
  };
294
+ /** Runs `then` once the saved ids are re-read (an account list); at once, in the same turn, when there is nothing to re-read. */
295
+ const afterSavingRefresh = (then: () => Promise<undefined>): Promise<undefined> => saving?.refresh ? saving.refresh().catch(() => undefined).then(then) : then();
279
296
  /** Filter and sort in ONE criteria change, so a tab that sets both runs one query, not two. */
280
297
  const setCriteria = (arg: unknown): void => {
281
298
  const input = object(arg);
@@ -329,15 +346,18 @@ export function decorateCollection(name: string, def: { state: State; actions?:
329
346
  if (backend) {
330
347
  actions.collectionDataChanged = s => derive(backend.apply(s, backend.controller.getState()));
331
348
  actions.load = (_s, arg) => {
332
- stashCopy(arg); syncSaved(); applyNavigationCriteria(arg, _s);
333
- const reset = backend.onLoad?.(arg);
334
- if (reset) { setCriteria(reset); persisted.write(prefs); }
335
- // A load of what the screen already shows is the screen coming back: it revalidates behind its rows.
336
- return backend.controller.query(criteria(), backend.restorePagesOnLoad, true).then(() => undefined);
349
+ stashCopy(arg);
350
+ return afterSavingRefresh(() => {
351
+ syncSaved(); applyNavigationCriteria(arg, _s);
352
+ const reset = backend.onLoad?.(arg);
353
+ if (reset) { setCriteria(reset); persisted.write(prefs); }
354
+ // A load of what the screen already shows is the screen coming back: it revalidates behind its rows.
355
+ return backend.controller.query(criteria(), backend.restorePagesOnLoad, true).then(() => undefined);
356
+ });
337
357
  };
338
358
  actions.refresh = (_s, arg) => {
339
- stashCopy(arg); syncSaved();
340
- return backend.controller.query(criteria()).then(() => undefined);
359
+ stashCopy(arg);
360
+ return afterSavingRefresh(() => { syncSaved(); return backend.controller.query(criteria()).then(() => undefined); });
341
361
  };
342
362
  actions.loadMore = () => backend.controller.loadMore().then(() => undefined);
343
363
  actions.retry = actions.collectionRetry = () => backend.controller.retry().then(() => undefined);
@@ -4565,7 +4565,7 @@ const SCREENS = runtimeSetting({
4565
4565
  "onAppear": {
4566
4566
  "actionId": "tier5.himiStoreSaved.load",
4567
4567
  "params": {
4568
- "copy": "{\"storeCommon.retryCta\":\"Try Again\",\"savedProducts.title\":\"Saved\",\"savedProducts.emptyTitle\":\"Nothing saved yet\",\"savedProducts.empty\":\"Tap the heart on a product to keep it here, on this device, for your next order.\",\"savedProducts.error\":\"Could not update your saved products. Try again.\",\"savedProducts.removeLabel\":\"Remove from saved\",\"savedProducts.addLabel\":\"Save\",\"savedProducts.browse\":\"Browse the Catalog\"}"
4568
+ "copy": "{\"storeCommon.retryCta\":\"Try Again\",\"savedProducts.title\":\"Saved\",\"savedProducts.emptyTitle\":\"Nothing saved yet\",\"savedProducts.empty\":\"Tap the heart on a product to keep it here for your next order.\",\"savedProducts.error\":\"Could not update your saved products. Try again.\",\"savedProducts.removeLabel\":\"Remove from saved\",\"savedProducts.addLabel\":\"Save\",\"savedProducts.browse\":\"Browse the Catalog\"}"
4569
4569
  }
4570
4570
  }
4571
4571
  }
@@ -16167,7 +16167,7 @@ const TEMPLATED: { pattern: string; display: string; liveSeed?: LiveSeed; static
16167
16167
  "onAppear": {
16168
16168
  "actionId": "tier5.himiStoreProduct.load",
16169
16169
  "params": {
16170
- "copy": "{\"storeCommon.retryCta\":\"Try Again\",\"product.navTitle\":\"Product\",\"product.addToCart\":\"Add to Cart\",\"product.viewCart\":\"View Cart\",\"product.emptyCta\":\"Back to the Catalog\",\"product.saveSuccess\":\"Saved.\",\"product.saveRemoved\":\"Removed from saved.\",\"product.saveError\":\"Could not update your saved products. Try again.\",\"product.quoteTitle\":\"Ordering in bulk?\",\"product.quoteBody\":\"Ask for a volume price on this product.\",\"product.quoteCta\":\"Request a Bulk Quote\",\"savedProducts.title\":\"Saved\",\"savedProducts.emptyTitle\":\"Nothing saved yet\",\"savedProducts.empty\":\"Tap the heart on a product to keep it here, on this device, for your next order.\",\"savedProducts.error\":\"Could not update your saved products. Try again.\",\"savedProducts.removeLabel\":\"Remove from saved\",\"savedProducts.addLabel\":\"Save\",\"savedProducts.browse\":\"Browse the Catalog\"}"
16170
+ "copy": "{\"storeCommon.retryCta\":\"Try Again\",\"product.navTitle\":\"Product\",\"product.addToCart\":\"Add to Cart\",\"product.viewCart\":\"View Cart\",\"product.emptyCta\":\"Back to the Catalog\",\"product.saveSuccess\":\"Saved.\",\"product.saveRemoved\":\"Removed from saved.\",\"product.saveError\":\"Could not update your saved products. Try again.\",\"product.quoteTitle\":\"Ordering in bulk?\",\"product.quoteBody\":\"Ask for a volume price on this product.\",\"product.quoteCta\":\"Request a Bulk Quote\",\"savedProducts.title\":\"Saved\",\"savedProducts.emptyTitle\":\"Nothing saved yet\",\"savedProducts.empty\":\"Tap the heart on a product to keep it here for your next order.\",\"savedProducts.error\":\"Could not update your saved products. Try again.\",\"savedProducts.removeLabel\":\"Remove from saved\",\"savedProducts.addLabel\":\"Save\",\"savedProducts.browse\":\"Browse the Catalog\"}"
16171
16171
  }
16172
16172
  }
16173
16173
  }
@@ -9,7 +9,10 @@ import type { MemberAvatarFactory } from './member-avatar.js';
9
9
 
10
10
  export interface CollectionSaving {
11
11
  read(): string[];
12
- write(ids: string[], rows: Record<string, unknown>[]): void;
12
+ /** May settle later (an account write); a rejection restores the selection and says so. */
13
+ write(ids: string[], rows: Record<string, unknown>[]): void | Promise<void>;
14
+ /** Re-read the saved ids `read` answers (an account list), before a load or refresh reads them. */
15
+ refresh?(): Promise<void>;
13
16
  }
14
17
  type State = Record<string, unknown>;
15
18
  interface BackendCollection {
@@ -267,19 +270,33 @@ export function decorateCollection(name: string, def: { state: State; actions?:
267
270
  const criteriaBefore = criteriaKey();
268
271
  const before = [...prefs.savedIds], undoBefore = lastUndo;
269
272
  update(arg, s);
273
+ const failed = () => {
274
+ prefs.savedIds = before; lastUndo = undoBefore;
275
+ saveMessage = copyParam('collection.saveError', 'Could not save this change. Try again.');
276
+ };
277
+ const finish = (settledLater: boolean) => {
278
+ persisted.write(prefs);
279
+ if (backend && config.backendQuery && criteriaBefore !== criteriaKey()) return backend.controller.query(criteria()).then(() => undefined);
280
+ // A write that settled later lands on the rows as they are now, not as they were when it began.
281
+ return derive(settledLater && backend ? backend.apply(s, backend.controller.getState()) : s);
282
+ };
270
283
  if (saving && JSON.stringify(before) !== JSON.stringify(prefs.savedIds)) {
284
+ let written: void | Promise<void>;
271
285
  try {
272
- saving.write(prefs.savedIds, Array.isArray(s[config.rows]) ? s[config.rows] as CollectionRow[] : []);
273
- saveMessage = '';
286
+ written = saving.write(prefs.savedIds, Array.isArray(s[config.rows]) ? s[config.rows] as CollectionRow[] : []);
274
287
  } catch {
275
- prefs.savedIds = before; lastUndo = undoBefore;
276
- saveMessage = copyParam('collection.saveError', 'Could not save this change. Try again.');
288
+ failed();
289
+ return finish(false);
290
+ }
291
+ if (written && typeof written.then === 'function') {
292
+ return written.then(() => { saveMessage = ''; return finish(true); }, () => { failed(); return finish(true); });
277
293
  }
294
+ saveMessage = '';
278
295
  }
279
- persisted.write(prefs);
280
- if (backend && config.backendQuery && criteriaBefore !== criteriaKey()) return backend.controller.query(criteria()).then(() => undefined);
281
- return derive(s);
296
+ return finish(false);
282
297
  };
298
+ /** Runs `then` once the saved ids are re-read (an account list); at once, in the same turn, when there is nothing to re-read. */
299
+ const afterSavingRefresh = (then: () => Promise<undefined>): Promise<undefined> => saving?.refresh ? saving.refresh().catch(() => undefined).then(then) : then();
283
300
  /** Filter and sort in ONE criteria change, so a tab that sets both runs one query, not two. */
284
301
  const setCriteria = (arg: unknown): void => {
285
302
  const input = object(arg);
@@ -333,19 +350,25 @@ export function decorateCollection(name: string, def: { state: State; actions?:
333
350
  if (backend) {
334
351
  actions.collectionDataChanged = s => derive(backend.apply(s, backend.controller.getState()));
335
352
  actions.load = (_s, arg) => {
336
- stashCopy(arg); syncSaved(); applyNavigationCriteria(arg, _s);
337
- const reset = backend.onLoad?.(arg);
338
- if (reset) { setCriteria(reset); persisted.write(prefs); }
339
- // A load of what the screen already shows is the screen coming back: it revalidates behind its rows.
340
- return backend.controller.query(criteria(), backend.restorePagesOnLoad, true).then(() => undefined);
353
+ stashCopy(arg);
354
+ return afterSavingRefresh(() => {
355
+ syncSaved(); applyNavigationCriteria(arg, _s);
356
+ const reset = backend.onLoad?.(arg);
357
+ if (reset) { setCriteria(reset); persisted.write(prefs); }
358
+ // A load of what the screen already shows is the screen coming back: it revalidates behind its rows.
359
+ return backend.controller.query(criteria(), backend.restorePagesOnLoad, true).then(() => undefined);
360
+ });
341
361
  };
342
362
  actions.refresh = (_s, arg) => {
343
- stashCopy(arg); syncSaved();
344
- // Reconnect refreshes the currently visible result. Rebuild every page the
345
- // user had already opened, using fresh cursors, before replacing the snapshot.
346
- return (backend.readLifecycle
347
- ? backend.controller.query(criteria(), true, true)
348
- : backend.controller.query(criteria())).then(() => undefined);
363
+ stashCopy(arg);
364
+ return afterSavingRefresh(() => {
365
+ syncSaved();
366
+ // Reconnect refreshes the currently visible result. Rebuild every page the
367
+ // user had already opened, using fresh cursors, before replacing the snapshot.
368
+ return (backend.readLifecycle
369
+ ? backend.controller.query(criteria(), true, true)
370
+ : backend.controller.query(criteria())).then(() => undefined);
371
+ });
349
372
  };
350
373
  actions.loadMore = () => backend.controller.loadMore().then(() => undefined);
351
374
  actions.retry = actions.collectionRetry = () => backend.controller.retry().then(() => undefined);
@@ -1,9 +1,13 @@
1
1
  import { withCollectionSaving, type CollectionSaving } from './collection-service.js';
2
- import { readSavedProducts, writeSavedProducts } from './himi-store-saved.js';
2
+ import { readSavedProducts, syncSavedProducts, writeSavedProducts } from './himi-store-saved.js';
3
3
 
4
4
  export const storeCollectionSaving: CollectionSaving = {
5
+ // A signed-in member's saved ids are their account wishlist, re-read before each load.
5
6
  read: () => readSavedProducts().map(row => row.id),
6
- write(ids, rows) {
7
+ refresh: () => syncSavedProducts(),
8
+ async write(ids, rows) {
9
+ // Whose list this is, now: a member's change goes to their account, a visitor's to the device.
10
+ await syncSavedProducts();
7
11
  const products = new Map(readSavedProducts().map(row => [row.id, row]));
8
12
  for (const row of rows) {
9
13
  if (typeof row.id !== 'string' || typeof row.name !== 'string') continue;
@@ -16,7 +20,7 @@ export const storeCollectionSaving: CollectionSaving = {
16
20
  }
17
21
  const selected = ids.map(id => products.get(id));
18
22
  if (selected.some(row => !row)) throw new Error('Saved product metadata is unavailable');
19
- writeSavedProducts(selected.filter((row): row is NonNullable<typeof row> => !!row));
23
+ await writeSavedProducts(selected.filter((row): row is NonNullable<typeof row> => !!row));
20
24
  },
21
25
  };
22
26
  export const defineService = withCollectionSaving(storeCollectionSaving);
@@ -1,5 +1,20 @@
1
- // Saved products use the host's durable, app-scoped KV, shared by screen workers.
1
+ // Saved products ("wishlist"). A signed-in member's list is their Wix account wishlist (eCommerce
2
+ // Wishlists, the list the Wix site and the One App show), so a product saved anywhere shows here.
3
+ // A visitor's list stays on this device in the host's durable, app-scoped KV, shared by screen workers.
4
+ // The two never mix: a member never sees the device list, and signing in copies nothing to the account.
2
5
  // Adapted from Hip Shop; a failed write must never claim that a save succeeded.
6
+ //
7
+ // Each worker keeps the member's list as last read (`syncSavedProducts`), so the synchronous readers
8
+ // (`readSavedProducts`, `isProductSaved`) answer for whoever was signed in at that read. Call
9
+ // `syncSavedProducts` in a load before reading, and `listSavedProducts` where the list is shown.
10
+ import { addWishlistItem, getDefaultWishlist, removeWishlistItem, type WixWishlist, type WixWishlistCatalogReference } from "@himalaya/wix-ecom";
11
+ import { productImage, productPrice, searchStoreProducts, type StoreProduct } from "./himi-store.js";
12
+ import { cleanTitle } from "./himi-text.js";
13
+ // The identity read is `member-access.ts`'s, inlined: that module imports @himalaya/wix-users, which node (tests
14
+ // importing shared sources) cannot resolve, so its legacy rung calls the same route through the ecom bridge.
15
+ import { dispatch } from "@himalaya/dispatch";
16
+ import { wixCall } from "@himalaya/wix-ecom";
17
+
3
18
  export interface SavedProduct {
4
19
  id: string;
5
20
  name: string;
@@ -10,13 +25,19 @@ export interface SavedProduct {
10
25
  }
11
26
  type StorageLike = { getItem(key: string): string | null; setItem(key: string, value: string): void };
12
27
  const KEY = "himi-store:saved-products:v1";
28
+ /** The Wix Stores app id. The One App and the account wishlist hold Stores products under it. */
29
+ const STORES_APP_ID = "1380b703-ce81-ff05-f115-39571d94dfcd";
30
+ /** The Stores catalog id eCommerce uses in cart and order references: a product saved under it is a Stores product too. */
31
+ const STORES_CATALOG_ID = "215238eb-22a5-4c36-9e7b-e7c08025e04e";
32
+ const STORES_APPS = new Set([STORES_APP_ID, STORES_CATALOG_ID]);
33
+
13
34
  function storage(): StorageLike {
14
35
  const host = globalThis as { himalaya?: { storage?: StorageLike }; localStorage?: StorageLike };
15
36
  const kv = host.himalaya?.storage ?? host.localStorage;
16
37
  if (!kv) throw new Error("Saved-product storage is unavailable");
17
38
  return kv;
18
39
  }
19
- export function readSavedProducts(): SavedProduct[] {
40
+ function readDeviceProducts(): SavedProduct[] {
20
41
  const raw = storage().getItem(KEY);
21
42
  if (!raw) return [];
22
43
  const parsed: unknown = JSON.parse(raw);
@@ -34,10 +55,7 @@ export function readSavedProducts(): SavedProduct[] {
34
55
  }
35
56
  return [...rows.values()];
36
57
  }
37
- export function isProductSaved(id: string): boolean {
38
- return readSavedProducts().some(row => row.id === id);
39
- }
40
- export function writeSavedProducts(rows: SavedProduct[]): void {
58
+ function writeDeviceProducts(rows: SavedProduct[]): void {
41
59
  const kv = storage();
42
60
  const value = JSON.stringify(rows);
43
61
  kv.setItem(KEY, value);
@@ -45,13 +63,257 @@ export function writeSavedProducts(rows: SavedProduct[]): void {
45
63
  // before displaying success; a missing/mismatched read is a failed save.
46
64
  if (kv.getItem(KEY) !== value) throw new Error("Saved-product write did not persist");
47
65
  }
48
- export function toggleSavedProduct(product: SavedProduct): boolean {
49
- if (!product.id.trim() || !product.name.trim()) throw new Error("No product to save");
50
- const rows = readSavedProducts();
51
- const saved = !rows.some(row => row.id === product.id);
52
- writeSavedProducts(saved ? [product, ...rows] : rows.filter(row => row.id !== product.id));
66
+
67
+ // ---- The signed-in member's account wishlist, as this worker last read it ----
68
+
69
+ interface MemberList {
70
+ /** Whose list: the site partition and the member, from `currentKey`. */
71
+ key: string;
72
+ /** Saved product ids, newest first. */
73
+ ids: string[];
74
+ /** The references each id is saved under: a variant saved on the website is its own item. */
75
+ refs: Map<string, WixWishlistCatalogReference[]>;
76
+ /** Product details for the ids, from the catalog or from the control that saved it. */
77
+ details: Map<string, SavedProduct>;
78
+ }
79
+ /** Whose list this worker answers, from its last read. Until a read says, nothing is saved: the device
80
+ * list may be a visitor's, and must never show for a member. */
81
+ let mode: "device" | "member" | undefined;
82
+ let member: MemberList | undefined;
83
+ /** Identity reads in flight. While one is, the synchronous readers answer nothing: the cached list may be
84
+ * the previous member's, or a visitor's, and a grid deriving its hearts now must not show it to whoever
85
+ * signed in since. */
86
+ let resolving = 0;
87
+ /** The newest `syncSavedProducts` call. An older read that lands after it never applies its answer. */
88
+ let syncGen = 0;
89
+ let latestSync: Promise<void> | undefined;
90
+ /** Bumped by every account write: a read that started before one never overwrites what it changed. */
91
+ let memberWrites = 0;
92
+ /** A toggle per product at a time: a second tap while the first is on the wire would read the same state. */
93
+ const toggles = new Map<string, Promise<boolean>>();
94
+
95
+ /** The error `member-access.ts`'s `memberAccessDenied` recognizes: the member changed under a read or write. */
96
+ function memberAccessChanged(): Error {
97
+ const error = new Error("Member access changed"); error.name = "MemberAccessChanged"; return error;
98
+ }
99
+ /** The member's email from the host, or "" for a visitor. A host without the identity action (an older
100
+ * binary) or one that fails it falls back, as `memberAccess` does, to the signed-in profile: only a 401 there
101
+ * says "visitor". Any other failure throws, so it is never read as a visitor and never answers the device list. */
102
+ async function signedInEmail(): Promise<{ signedIn: boolean; email: string }> {
103
+ type Identity = { status?: unknown; ok?: unknown; email?: unknown; signedIn?: unknown; payload?: { email?: unknown; signedIn?: unknown } } | null;
104
+ try {
105
+ const value = await dispatch("himi.wix.memberIdentity") as Identity;
106
+ if (value?.status === "error" || value?.ok === false) throw value;
107
+ const raw = value?.email ?? value?.payload?.email;
108
+ const email = typeof raw === "string" ? raw.trim().toLowerCase() : "";
109
+ return { signedIn: (value?.signedIn ?? value?.payload?.signedIn) === true || !!email, email };
110
+ } catch { /* the legacy rung below */ }
111
+ // No Wix bridge, no Wix session: nobody can be signed in.
112
+ if (!(globalThis as { himalaya?: { wixApi?: unknown } }).himalaya?.wixApi) return { signedIn: false, email: "" };
113
+ try {
114
+ const profile = await wixCall<{ email?: unknown; contactEmail?: unknown }>("GET", "https://users.wix.com/wix-users/v1/users/my-data?includeProfile=true");
115
+ const raw = profile?.email ?? profile?.contactEmail;
116
+ const email = typeof raw === "string" ? raw.trim().toLowerCase() : "";
117
+ return { signedIn: !!email, email };
118
+ } catch (error) {
119
+ const failure = error as { status?: unknown; statusCode?: unknown; code?: unknown; message?: unknown } | null;
120
+ const anonymous = failure?.status === 401 || failure?.statusCode === 401 || failure?.code === "UNAUTHENTICATED"
121
+ || /^HTTP\s*401\b/i.test(String(failure?.message ?? ""));
122
+ // A web bridge refuses the owner-scoped profile route outright (`webwix_owner_only`): that host cannot tell
123
+ // through this rung, as `memberAccess` reads it too, so its session is a visitor's, never an error.
124
+ const ownerOnly = failure?.code === "webwix_owner_only";
125
+ if (anonymous || ownerOnly) return { signedIn: false, email: "" };
126
+ throw new Error("Who is signed in could not be read", { cause: error });
127
+ }
128
+ }
129
+ /** Who is signed in, as a key for their list: the host's account and site partition plus the member's
130
+ * email; undefined for a visitor. Throws when it cannot tell. */
131
+ async function currentKey(): Promise<string | undefined> {
132
+ const { signedIn, email } = await signedInEmail();
133
+ if (!signedIn) return undefined;
134
+ const input = (globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input;
135
+ return JSON.stringify([input?.__himiPreferenceAccount ?? "", input?.__himiPreferenceBusiness ?? "", email]);
136
+ }
137
+ async function assertKey(key: string): Promise<void> {
138
+ if ((await currentKey()) !== key) throw memberAccessChanged();
139
+ }
140
+
141
+ function applyWishlist(key: string, wishlist: WixWishlist | undefined): void {
142
+ const items = [...(wishlist?.items ?? [])].sort((a, b) => Date.parse(b.addedDate ?? "") - Date.parse(a.addedDate ?? "") || 0);
143
+ const refs = new Map<string, WixWishlistCatalogReference[]>();
144
+ for (const item of items) {
145
+ const ref = item.catalogReference;
146
+ const id = typeof ref?.catalogItemId === "string" ? ref.catalogItemId.trim() : "";
147
+ if (!id || !STORES_APPS.has(ref?.appId ?? "")) continue;
148
+ refs.set(id, [...(refs.get(id) ?? []), ref!]);
149
+ }
150
+ const details = member?.key === key ? member.details : new Map<string, SavedProduct>();
151
+ member = { key, ids: [...refs.keys()], refs, details };
152
+ }
153
+
154
+ /**
155
+ * Resolve who is signed in and, for a member, read their account wishlist. A visitor's reads then
156
+ * answer the device list. Throws when the member's wishlist cannot be read; the synchronous readers
157
+ * then answer nothing for that member (never the device list), so a heart shows unsaved until a retry.
158
+ * A read that finishes after the member changed is read again for whoever is signed in now.
159
+ */
160
+ export function syncSavedProducts(): Promise<void> {
161
+ const gen = ++syncGen;
162
+ const run = runSync(gen);
163
+ latestSync = run;
164
+ return run;
165
+ }
166
+ async function runSync(gen: number): Promise<void> {
167
+ let memberChanged = false;
168
+ for (let attempt = 0; attempt < 3; attempt++) {
169
+ let key: string | undefined;
170
+ resolving++;
171
+ try {
172
+ // Unknown identity: nothing is answered (never the device list) until a read can tell.
173
+ try { key = await currentKey(); } catch (error) { mode = undefined; member = undefined; throw error; }
174
+ if (key === undefined) { mode = "device"; member = undefined; return; }
175
+ mode = "member";
176
+ if (member?.key !== key) member = { key, ids: [], refs: new Map(), details: new Map() };
177
+ } finally { resolving--; }
178
+ const writes = memberWrites;
179
+ const { wishlist } = await getDefaultWishlist();
180
+ // A newer read started while this one was on the wire: its answer is the newer one. Wait for it.
181
+ if (gen !== syncGen && latestSync) return latestSync;
182
+ memberChanged = (await currentKey()) !== key;
183
+ // A save that landed while this read was on the wire is newer than it: read again.
184
+ if (memberChanged || writes !== memberWrites) continue;
185
+ applyWishlist(key, wishlist);
186
+ return;
187
+ }
188
+ throw memberChanged ? memberAccessChanged() : new Error("Saved products changed while they were read");
189
+ }
190
+
191
+ function detailsOf(p: StoreProduct): SavedProduct {
192
+ const name = cleanTitle(p.name ?? "") || "Product";
193
+ return { id: p.id ?? "", name, price: productPrice(p), image: productImage(p) };
194
+ }
195
+
196
+ /** The saved list as the saved-products screen and the wishlist sections show it. A member's ids come
197
+ * from their account wishlist and the details from the catalog; a product the store no longer has is
198
+ * left out. A visitor's list is the device list. */
199
+ export async function listSavedProducts(): Promise<SavedProduct[]> {
200
+ await syncSavedProducts();
201
+ if (mode !== "member" || !member) return readDeviceProducts();
202
+ const list = member;
203
+ if (list.ids.length) {
204
+ // A wishlist holds at most 100 items: one page. Fresh details every time, so a price change shows.
205
+ const { products } = await searchStoreProducts({ ids: list.ids, limit: 100 });
206
+ await assertKey(list.key);
207
+ const found = new Map((products ?? []).map(p => [p.id ?? "", p]));
208
+ for (const id of list.ids) {
209
+ const product = found.get(id);
210
+ if (product) list.details.set(id, { ...list.details.get(id), ...detailsOf(product) });
211
+ else list.details.delete(id);
212
+ }
213
+ }
214
+ return list.ids.flatMap(id => list.details.get(id) ?? []);
215
+ }
216
+
217
+ /** The saved list as this worker last read it (see `syncSavedProducts`): empty before the first read.
218
+ * A member's product whose details were never read has an empty name: read ids from it, list with
219
+ * `listSavedProducts`. */
220
+ export function readSavedProducts(): SavedProduct[] {
221
+ if (mode === undefined || resolving > 0) return [];
222
+ if (mode === "member") {
223
+ const list = member;
224
+ if (!list) return [];
225
+ return list.ids.map(id => list.details.get(id) ?? { id, name: "", price: "", image: "" });
226
+ }
227
+ return readDeviceProducts();
228
+ }
229
+ export function isProductSaved(id: string): boolean {
230
+ if (mode === undefined || resolving > 0) return false;
231
+ if (mode === "member") return !!member?.ids.includes(id);
232
+ return readDeviceProducts().some(row => row.id === id);
233
+ }
234
+
235
+ async function memberKeyForWrite(): Promise<string | undefined> {
236
+ const key = await currentKey();
237
+ if (key === undefined) { mode = "device"; member = undefined; return undefined; }
238
+ if (mode !== "member" || member?.key !== key) await syncSavedProducts();
239
+ if (member?.key !== key) throw memberAccessChanged();
240
+ return key;
241
+ }
242
+
243
+ /** Save or unsave one product in the member's account wishlist. The control's own state is not trusted:
244
+ * an unsave removes every reference the product is saved under. Throws when the member changed during
245
+ * the write, so the caller reloads for whoever is signed in now. */
246
+ async function writeMemberProduct(key: string, product: SavedProduct, saved: boolean): Promise<void> {
247
+ const list = member!;
248
+ const refs = saved ? [{ catalogItemId: product.id, appId: STORES_APP_ID }] : list.refs.get(product.id) ?? [{ catalogItemId: product.id, appId: STORES_APP_ID }];
249
+ let wishlist: WixWishlist | undefined;
250
+ memberWrites++;
251
+ try {
252
+ for (const ref of refs) wishlist = (saved ? await addWishlistItem(ref) : await removeWishlistItem(ref)).wishlist ?? wishlist;
253
+ } catch (error) {
254
+ // A refusal that lands after the member changed is the member change, so the caller reloads for whoever
255
+ // is signed in now; for the same member it is a failed write.
256
+ if ((await currentKey().catch(() => undefined)) !== key) throw memberAccessChanged();
257
+ throw error;
258
+ }
259
+ await assertKey(key);
260
+ if (wishlist) applyWishlist(key, wishlist);
261
+ else if (saved) { list.ids = [product.id, ...list.ids.filter(id => id !== product.id)]; list.refs.set(product.id, refs); }
262
+ else { list.ids = list.ids.filter(id => id !== product.id); list.refs.delete(product.id); }
263
+ if (saved && product.name.trim()) member!.details.set(product.id, product);
264
+ }
265
+
266
+ /** Replace the whole saved list (a collection's multi-select save). A member's account wishlist gets
267
+ * only the difference; a visitor's device list is written as given. */
268
+ export async function writeSavedProducts(rows: SavedProduct[]): Promise<void> {
269
+ const key = await memberKeyForWrite();
270
+ if (key === undefined) { writeDeviceProducts(rows); return; }
271
+ const wanted = new Map(rows.map(row => [row.id, row]));
272
+ for (const id of [...member!.ids]) if (!wanted.has(id)) await writeMemberProduct(key, { id, name: "", price: "", image: "" }, false);
273
+ for (const row of [...rows].reverse()) if (!member!.ids.includes(row.id)) await writeMemberProduct(key, row, true);
274
+ }
275
+
276
+ /** Save or unsave a product; answers the new saved state. A member's save is in their account wishlist. */
277
+ export function toggleSavedProduct(product: SavedProduct): Promise<boolean> {
278
+ if (!product.id.trim() || !product.name.trim()) return Promise.reject(new Error("No product to save"));
279
+ const pending = toggles.get(product.id);
280
+ if (pending) return pending;
281
+ const toggle = toggleOnce(product).finally(() => toggles.delete(product.id));
282
+ toggles.set(product.id, toggle);
283
+ return toggle;
284
+ }
285
+ async function toggleOnce(product: SavedProduct): Promise<boolean> {
286
+ const key = await memberKeyForWrite();
287
+ if (key === undefined) {
288
+ const rows = readDeviceProducts();
289
+ const saved = !rows.some(row => row.id === product.id);
290
+ writeDeviceProducts(saved ? [product, ...rows] : rows.filter(row => row.id !== product.id));
291
+ return saved;
292
+ }
293
+ const saved = !member!.ids.includes(product.id);
294
+ await writeMemberProduct(key, product, saved);
53
295
  return saved;
54
296
  }
55
- export function removeSavedProduct(id: string): void {
56
- writeSavedProducts(readSavedProducts().filter(row => row.id !== id));
297
+ export async function removeSavedProduct(id: string): Promise<void> {
298
+ const key = await memberKeyForWrite();
299
+ if (key === undefined) { writeDeviceProducts(readDeviceProducts().filter(row => row.id !== id)); return; }
300
+ await writeMemberProduct(key, { id, name: "", price: "", image: "" }, false);
301
+ }
302
+
303
+ /** Tests only: forget the member list this worker read. */
304
+ export function __resetSavedProductsForTests(): void { mode = undefined; member = undefined; toggles.clear(); }
305
+
306
+ /** Read the saved list in the background and, when the saved ids changed, run `apply` (a grid's re-derive of
307
+ * its CURRENT state), so hearts follow the signed-in member without holding the page. A failed read leaves the
308
+ * hearts as the last read left them (unsaved for a member never read). */
309
+ export function refreshSavedThen(apply: () => unknown): void {
310
+ // Storage a host does not offer is no saved product: hearts are optional, a failure never fails the screen.
311
+ const ids = () => { try { return JSON.stringify(readSavedProducts().map(row => row.id)); } catch { return "[]"; } };
312
+ const whose = () => `${mode ?? ""}:${member?.key ?? ""}`;
313
+ // Snapshot BEFORE the sync starts: once it does, the readers answer nothing until it knows who is signed in.
314
+ const before = ids(), beforeWhose = whose();
315
+ // Re-derive whenever a grid may show something else now: the list or its owner changed, or there are saves
316
+ // (a grid that derived while the identity read was in flight drew none). Only "nothing, as before" skips it.
317
+ const settle = () => { const now = ids(); if (now !== before || whose() !== beforeWhose || now !== "[]") apply(); };
318
+ void syncSavedProducts().then(settle, settle);
57
319
  }