@wix/himalaya-cli 0.1672.0 → 0.1673.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 (33) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/legacy-import/src/index.d.ts +16 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/legacy-import.d.ts +21 -3
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +14 -2
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/legacy-import.mjs +32 -1
  5. package/dist/browser-plane/assets.json +5 -5
  6. package/dist/browser-plane/preview-deferred/{cf2ac6865a1e6be5cccec4f2538bf18bbbf121a5f5971ad46212bf3a848ec35c.bin → 0f5533bf4197dc43489701db18378cecdb02db230a0fc2603e764999544513da.bin} +1 -1
  7. package/dist/browser-plane/sw.js +6 -6
  8. package/dist/cli.mjs +38 -38
  9. package/dist/preview-assets.generated.bin +0 -0
  10. package/guides/sdk-reference.json +15 -1
  11. package/guides/web-page-sdk-reference.md +1 -1
  12. package/package.json +2 -2
  13. package/templates/beauty-salon/l10n/en.json +1 -1
  14. package/templates/branded-lite/dev/index.ts +6607 -2231
  15. package/templates/branded-lite/l10n/en.json +25 -15
  16. package/templates/branded-lite/l10n/he.json +34 -34
  17. package/templates/branded-lite/tier5-src/_shared/himi-cms.ts +10 -3
  18. package/templates/branded-lite/tier5-src/himi-branded-lite-cms/index.ts +7 -0
  19. package/templates/branded-lite/tier5-src/himi-branded-lite-cms-collection/index.ts +527 -138
  20. package/templates/community-club/dev/index.ts +2459 -271
  21. package/templates/community-club/l10n/en.json +16 -11
  22. package/templates/community-club/l10n/he.json +38 -34
  23. package/templates/community-club/tier5-src/_shared/himi-cms.ts +10 -3
  24. package/templates/community-club/tier5-src/himi-branded-lite-cms/index.ts +7 -0
  25. package/templates/community-club/tier5-src/himi-branded-lite-cms-collection/index.ts +527 -138
  26. package/templates/events-meetups/l10n/en.json +1 -1
  27. package/templates/gym-fitness/l10n/en.json +1 -1
  28. package/templates/nonprofit-cause/l10n/en.json +1 -1
  29. package/templates/podcast-creator/l10n/en.json +1 -1
  30. package/templates/portfolio-creative/l10n/en.json +1 -1
  31. package/templates/restaurant/l10n/en.json +1 -1
  32. package/templates/retail-store/l10n/en.json +1 -1
  33. package/templates/yoga-studio/l10n/en.json +1 -1
@@ -1,14 +1,16 @@
1
- import { defineService } from "../_shared/collection-service.js";
1
+ import { defineService, decorateCollection } from "../_shared/collection-service.js";
2
2
  import {
3
3
  collectionArg,
4
4
  collectionDefinitions,
5
+ countDataItems,
5
6
  queryDataItems,
6
7
  type CmsCollectionDefinition,
7
8
  type CmsFieldDefinition,
8
9
  type WixDataItem,
9
10
  } from "../_shared/himi-cms";
10
11
  import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
11
- import { getAll, upsert, type DbEntity } from "@himalaya/local-db";
12
+ import { get, getAll, upsert, type DbEntity } from "@himalaya/local-db";
13
+ import { appLocale, businessTimeZone } from "../_shared/app-locale.js";
12
14
  import { formatDateMedium } from "../_shared/engine-intl.js";
13
15
  import { openRichLink } from "../_shared/rich-content-link.js";
14
16
  import { richBody, ROW_IMAGE_WIDTH } from "../_shared/rich-body.js";
@@ -17,32 +19,106 @@ import { richBody, ROW_IMAGE_WIDTH } from "../_shared/rich-body.js";
17
19
  // the on-device `cms_items` store. Rows are cached per collection (the persisted key is
18
20
  // namespaced with the collection id, the in-memory ItemRow keeps its real id) so an
19
21
  // offline load repaints the last-synced items for THIS collection without mixing others.
20
- // DEGRADES GRACEFULLY: every local-db call is wrapped so a build without the
21
- // `local_database` grant (+ declared `cms_items`) falls back to today's online-only path.
22
+ // Only page 1 of the default view is cached. DEGRADES GRACEFULLY: every local-db call is
23
+ // wrapped so a build without the `local_database` grant (+ declared `cms_items`) falls
24
+ // back to today's online-only path.
22
25
  const ENTITY = "cms_items";
23
26
  function cacheKey(collectionId: string, rowId: string): string { return `${collectionId}::${rowId}`; }
24
- async function readCached(collectionId: string): Promise<ItemRow[]> {
27
+ // Outside the legacy item-key namespace, so old rows remain a migration fallback.
28
+ function pageCacheKey(collectionId: string): string { return `@cms-first-page:${encodeURIComponent(collectionId)}`; }
29
+ function accessKey(collectionId: string): string { return `@cms-access:${encodeURIComponent(collectionId)}`; }
30
+ function accessFence(row: DbEntity | null | undefined): string | null {
31
+ if (!row) return "";
32
+ return row.cachePageKind === "cms-revocation" && row.cachePageVersion === 1 && typeof row.cacheAccessFence === "string" && row.cacheAccessFence.length > 0
33
+ ? row.cacheAccessFence : null;
34
+ }
35
+ async function readAccessFence(collectionId: string): Promise<string | null | undefined> {
36
+ try { return accessFence(await get(ENTITY, accessKey(collectionId))); } catch { return undefined; }
37
+ }
38
+ let cacheWriteTail: Promise<void> = Promise.resolve();
39
+ function legacyText(value: string | undefined, collection: CmsCollectionDefinition): string {
40
+ if (!value) return "";
41
+ const field = collection.fields.find((candidate) => value.startsWith(`${candidate.displayName}: `));
42
+ return field ? value.slice(field.displayName.length + 2) : value;
43
+ }
44
+ async function readCached(collectionId: string, collection: CmsCollectionDefinition): Promise<{ rows: ItemRow[]; accessFence: string | null }> {
25
45
  try {
26
46
  const prefix = `${collectionId}::`;
27
- const rows = await getAll(ENTITY);
28
- // A row cached before [rico] #3372 carries no document fields: it shows its plain text.
29
- return rows
47
+ // A revisit must observe any queued authorization purge before reviving rows.
48
+ await cacheWriteTail;
49
+ const stored = await getAll(ENTITY);
50
+ const fence = accessFence(stored.find(row => row.id === accessKey(collectionId)));
51
+ const empty = { rows: [], accessFence: fence };
52
+ if (fence === null) return empty;
53
+ const snapshot = stored.find(row => row.id === pageCacheKey(collectionId));
54
+ // A response started before another worker's denial cannot re-prime its cache.
55
+ if ((snapshot?.cacheAccessFence ?? "") !== fence) return empty;
56
+ if (snapshot && (snapshot.cachePageKind !== "cms-first-page" || snapshot.cachePageVersion !== 1 || typeof snapshot.rowsJson !== "string")) return empty;
57
+ // A snapshot is authoritative even when empty; legacy insertion order must
58
+ // not replace the latest successful first-page order after an upgrade.
59
+ const rows = snapshot ? JSON.parse(String(snapshot.rowsJson)) as DbEntity[] : stored;
60
+ if (!Array.isArray(rows)) return empty;
61
+ // A row cached by an older build carries other fields: keep what still applies, default the rest.
62
+ return { accessFence: fence, rows: rows
30
63
  .filter((r) => typeof r.id === "string" && r.id.startsWith(prefix))
31
- .map((r) => ({ bodyJson: "", hasBodyJson: false, bodyText: "", ...(r as unknown as Partial<ItemRow>), id: (r.id as string).slice(prefix.length) }) as ItemRow);
32
- } catch { return []; }
64
+ // Older releases cached fifty rows; revive only this version's first page.
65
+ .slice(0, PAGE_SIZE)
66
+ .map((r) => {
67
+ const cached = r as unknown as Partial<ItemRow> & { subtitle?: string };
68
+ const legacy = cached.summary === undefined;
69
+ return finishRow({
70
+ id: (r.id as string).slice(prefix.length),
71
+ title: cached.title ?? "",
72
+ fallbackIndex: cached.fallbackIndex,
73
+ primaryDate: cached.primaryDate,
74
+ metaDate: cached.metaDate,
75
+ metaSuffix: cached.metaSuffix,
76
+ summary: cached.summary ?? legacyText(cached.subtitle, collection),
77
+ meta: legacy ? legacyText(cached.meta, collection) : cached.meta ?? "",
78
+ image: cached.image ?? "",
79
+ bodyJson: cached.bodyJson ?? "",
80
+ bodyText: cached.bodyText ?? "",
81
+ }, collection);
82
+ }) };
83
+ } catch { return { rows: [], accessFence: null }; }
33
84
  }
34
- async function writeCached(collectionId: string, rows: ItemRow[]): Promise<void> {
35
- try { for (const r of rows) await upsert(ENTITY, { ...(r as unknown as DbEntity), id: cacheKey(collectionId, r.id) }); } catch { /* capability not granted → online-only */ }
85
+ async function writeCached(collectionId: string, rows: ItemRow[], generation: number, fence: string | null): Promise<void> {
86
+ // One replace preserves order/deletions/empty results. Serialize already-started
87
+ // writes so an old native acknowledgement cannot leave an older snapshot last.
88
+ const write = cacheWriteTail.then(async () => {
89
+ if (fence === null || generation !== firstPageGeneration) return;
90
+ await upsert(ENTITY, {
91
+ id: pageCacheKey(collectionId), cachePageKind: "cms-first-page", cachePageVersion: 1, cacheAccessFence: fence,
92
+ rowsJson: JSON.stringify(rows.slice(0, PAGE_SIZE).map(row => ({ ...row, expanded: false, collapsed: true, id: cacheKey(collectionId, row.id) }))),
93
+ });
94
+ });
95
+ cacheWriteTail = write.catch(() => { /* capability not granted → online-only */ });
96
+ await cacheWriteTail;
36
97
  }
37
98
 
99
+ const PAGE_SIZE = 20;
100
+ /** The second text field joins the meta line only when it is this short (a category, not a paragraph). */
101
+ const META_FIELD_MAX_CHARS = 24;
102
+ /** The newest-first default: Wix's own created date, present on every collection. */
103
+ const DEFAULT_SORT = [{ fieldName: "_createdDate", order: "DESC" as const }];
104
+
38
105
  interface ItemRow {
39
106
  id: string;
40
107
  title: string;
41
- subtitle: string;
108
+ /** Raw presentation inputs let a warm language change reformat without another read. */
109
+ fallbackIndex?: number;
110
+ primaryDate?: string;
111
+ metaDate?: string;
112
+ metaSuffix?: string;
113
+ /** The first TEXT / RICH_TEXT field that is not the display field — no "Label:" prefix. */
114
+ summary: string;
115
+ /** The first DATE field, then a short second text field, joined with " · ". */
42
116
  meta: string;
43
117
  image: string;
44
- initial: string;
45
118
  hasImage: boolean;
119
+ /** The collection has an IMAGE field: every row reserves the 72x72 slot, an empty one draws a tile. */
120
+ hasMedia: boolean;
121
+ noMedia: boolean;
46
122
  noImage: boolean;
47
123
  /** [rico] #3372 — the item's first RICH_CONTENT field as ONE document string for the row's RichContent; ""
48
124
  * when the collection has none, the item left it empty, or the encoder rejected it. */
@@ -51,49 +127,149 @@ interface ItemRow {
51
127
  hasBodyJson: boolean;
52
128
  /** That field's plain text: the RichContent fallback. */
53
129
  bodyText: string;
130
+ /** Long text or a body: the row expands in place and shows the chevron. */
131
+ expandable: boolean;
132
+ /** Finite descriptor variant: passive rows never expose a no-op action. */
133
+ rowVariant: "static" | "expandable";
134
+ noChevron: boolean;
135
+ expanded: boolean;
136
+ collapsed: boolean;
137
+ expandHint: string;
138
+ expansionValue: string;
54
139
  }
55
140
 
56
- interface State {
141
+ type ErrorKind = "" | "offline" | "server" | "signIn" | "permission";
142
+
143
+ /** What the worker knows; every flag below is derived from it. */
144
+ interface Facts {
145
+ cacheAccessFence: string;
57
146
  status: "loading" | "ready" | "error";
58
147
  collectionName: string;
59
148
  collectionId: string;
60
- accessLabel: string;
61
- all: ItemRow[];
149
+ hasMedia: boolean;
62
150
  rows: ItemRow[];
151
+ /** "12 items" from countDataItems; "" until it arrives, and for good when the count fails. */
152
+ countText: string;
153
+ countTotal: number | null;
154
+ countPending: boolean;
155
+ /** Avoid a duplicate boot/onAppear read; a stale warm visit revalidates in place. */
156
+ lastSuccessAt: number;
157
+ nextCursor: string;
158
+ loadingMore: boolean;
159
+ pageError: boolean;
160
+ refreshFailed: boolean;
161
+ refreshing: boolean;
162
+ errorKind: ErrorKind;
163
+ // Ready for the search, sort and category filter of the next PR; nothing reads or sets them yet.
164
+ query: string;
165
+ sort: string;
166
+ category: string;
167
+ }
168
+
169
+ interface State extends Facts {
170
+ /** Shared collection projection; its preferences have their own scoped store. */
171
+ collection?: unknown;
172
+ noCount: boolean;
173
+ noCountSkeleton: boolean;
174
+ /** What the grid's pagination binds: empty while a page loads or failed, so a failed page is not fetched in a loop. */
175
+ pagingCursor: string;
63
176
  emptyText: string;
64
- errorText: string;
65
- isLoading: boolean;
66
- notLoading: boolean;
67
- isErrored: boolean;
68
- notErrored: boolean;
69
- noRows: boolean;
70
- noEmpty: boolean;
177
+ // Exclusive by construction: one status, one flag. The descriptor hides a node when its `hide*` mirror is true
178
+ // (there is no show-when modifier), so each node's visibility is one worker flag.
179
+ showLoading: boolean;
180
+ showRows: boolean;
181
+ showEmpty: boolean;
182
+ showRetryableError: boolean;
183
+ showSignInError: boolean;
184
+ showPermissionError: boolean;
185
+ showRefreshBanner: boolean;
186
+ showPageError: boolean;
187
+ hideLoading: boolean;
188
+ hideRows: boolean;
189
+ hideEmpty: boolean;
190
+ hideRetryableError: boolean;
191
+ hideSignInError: boolean;
192
+ hidePermissionError: boolean;
193
+ hideRefreshBanner: boolean;
194
+ hidePageError: boolean;
195
+ hideLoadingMore: boolean;
196
+ hideMediaSkeleton: boolean;
71
197
  }
72
198
 
73
- const initial: State = {
74
- status: "loading",
75
- collectionName: "",
76
- collectionId: "",
77
- accessLabel: "",
78
- all: [],
79
- rows: [],
80
- emptyText: "",
81
- errorText: "",
82
- isLoading: true,
83
- notLoading: false,
84
- isErrored: false,
85
- notErrored: true,
86
- noRows: true,
87
- noEmpty: true,
88
- };
199
+ function derive(f: Facts): State {
200
+ const countText = typeof f.countTotal === "number" ? countLine(f.countTotal) : f.countText;
201
+ const hasRows = f.rows.length > 0;
202
+ const failed = f.status === "error";
203
+ const show = {
204
+ showLoading: f.status === "loading",
205
+ showRows: f.status === "ready" && hasRows,
206
+ showEmpty: f.status === "ready" && !hasRows,
207
+ showRetryableError: failed && (f.errorKind === "offline" || f.errorKind === "server"),
208
+ showSignInError: failed && f.errorKind === "signIn",
209
+ showPermissionError: failed && f.errorKind === "permission",
210
+ showRefreshBanner: f.status === "ready" && hasRows && f.refreshFailed,
211
+ showPageError: f.status === "ready" && hasRows && f.pageError,
212
+ };
213
+ return {
214
+ ...f,
215
+ countText,
216
+ ...show,
217
+ hideLoading: !show.showLoading,
218
+ hideRows: !show.showRows,
219
+ hideEmpty: !show.showEmpty,
220
+ hideRetryableError: !show.showRetryableError,
221
+ hideSignInError: !show.showSignInError,
222
+ hidePermissionError: !show.showPermissionError,
223
+ hideRefreshBanner: !show.showRefreshBanner,
224
+ hidePageError: !show.showPageError,
225
+ hideLoadingMore: !(show.showRows && f.loadingMore),
226
+ hideMediaSkeleton: !f.hasMedia,
227
+ noCount: countText === "",
228
+ noCountSkeleton: !(f.countPending && !countText && !failed),
229
+ pagingCursor: f.refreshing || f.loadingMore || f.pageError ? "" : f.nextCursor,
230
+ emptyText: copyParam("cmsCollection.emptyText", "This collection has no published items yet."),
231
+ };
232
+ }
233
+
234
+ function facts(collection: CmsCollectionDefinition | undefined, over: Partial<Facts> = {}): Facts {
235
+ return {
236
+ cacheAccessFence: "",
237
+ status: "loading",
238
+ collectionName: collection?.displayName ?? "",
239
+ collectionId: collection?.id ?? "",
240
+ hasMedia: collection ? hasImageField(collection) : false,
241
+ rows: [],
242
+ countText: "",
243
+ countTotal: null,
244
+ countPending: true,
245
+ lastSuccessAt: 0,
246
+ nextCursor: "",
247
+ loadingMore: false,
248
+ pageError: false,
249
+ refreshFailed: false,
250
+ refreshing: false,
251
+ errorKind: "",
252
+ query: "",
253
+ sort: "newest",
254
+ category: "",
255
+ ...over,
256
+ };
257
+ }
258
+
259
+ function hasImageField(collection: CmsCollectionDefinition): boolean {
260
+ return collection.fields.some((field) => field.type.includes("IMAGE"));
261
+ }
262
+
263
+ function rawDate(value: unknown): string {
264
+ const raw = typeof value === "string" ? value : value && typeof value === "object" ? (value as { $date?: unknown }).$date : undefined;
265
+ return typeof raw === "string" ? raw : "";
266
+ }
89
267
 
90
268
  function dateValue(value: unknown): string {
91
- const raw = typeof value === "string"
92
- ? value
93
- : (value && typeof value === "object" ? (value as { $date?: unknown }).$date : undefined);
94
- if (typeof raw !== "string") return "";
269
+ const raw = rawDate(value);
270
+ if (!raw) return "";
95
271
  const date = new Date(raw);
96
- return Number.isNaN(date.getTime()) ? raw : formatDateMedium(date);
272
+ return Number.isNaN(date.getTime()) ? raw : formatDateMedium(date, appLocale(), businessTimeZone() || undefined);
97
273
  }
98
274
 
99
275
  /** [rico] #3372 — RICH_TEXT is HTML: its text, with the tags removed and the common entities decoded, so a
@@ -139,53 +315,84 @@ function imageValue(data: Record<string, unknown>, fields: CmsFieldDefinition[])
139
315
  return "";
140
316
  }
141
317
 
318
+ /** The row fields derived from the stored ones (also used when a cached row is revived). */
319
+ function finishRow(
320
+ base: Pick<ItemRow, "id" | "title" | "summary" | "meta" | "image" | "bodyJson" | "bodyText"> & Partial<Pick<ItemRow, "fallbackIndex" | "primaryDate" | "metaDate" | "metaSuffix">>,
321
+ collection: CmsCollectionDefinition,
322
+ ): ItemRow {
323
+ const hasMedia = hasImageField(collection);
324
+ // Rendered overflow depends on width and Dynamic Type, not character count. Every
325
+ // nonempty summary can be revealed; empty rows never offer an expansion affordance.
326
+ const expandable = base.bodyJson !== "" || base.bodyText !== "" || base.summary.trim() !== "";
327
+ return {
328
+ ...base,
329
+ hasImage: base.image !== "",
330
+ hasMedia,
331
+ noMedia: !hasMedia,
332
+ noImage: base.image === "",
333
+ hasBodyJson: base.bodyJson !== "",
334
+ expandable,
335
+ rowVariant: expandable ? "expandable" : "static",
336
+ noChevron: !expandable,
337
+ expanded: false,
338
+ collapsed: true,
339
+ expandHint: expandable ? copyParam("cmsCollection.expandHint", "Shows the full text") : "",
340
+ expansionValue: expandable ? copyParam("cmsCollection.collapsedValue", "Collapsed") : "",
341
+ };
342
+ }
343
+
344
+ function setRowExpanded(row: ItemRow, expanded: boolean): ItemRow {
345
+ return { ...row, expanded, collapsed: !expanded,
346
+ expansionValue: copyParam(expanded ? "cmsCollection.expandedValue" : "cmsCollection.collapsedValue", expanded ? "Expanded" : "Collapsed"),
347
+ expandHint: copyParam(expanded ? "cmsCollection.collapseHint" : "cmsCollection.expandHint", expanded ? "Hides the full text" : "Shows the full text"),
348
+ };
349
+ }
350
+
351
+ /** Only run on a load/copy handover, not on every row tap or publish. Legacy cached
352
+ * rows without raw inputs retain their last display text until the next read. */
353
+ function localizeState(state: State): State {
354
+ const rows = state.rows.map(row => {
355
+ const title = row.fallbackIndex !== undefined
356
+ ? copyTemplate("cmsCollection.itemFallbackTitle", "Item {n}", {n:row.fallbackIndex})
357
+ : row.primaryDate ? dateValue(row.primaryDate) : row.title;
358
+ const meta = row.metaDate !== undefined
359
+ ? [dateValue(row.metaDate), row.metaSuffix].filter(Boolean).join(" · ") : row.meta;
360
+ const next = {...row,title,meta};
361
+ return row.expandable ? setRowExpanded(next,row.expanded) : next;
362
+ });
363
+ const next = derive({...state,rows});
364
+ if (published === state) published = next;
365
+ return next;
366
+ }
367
+
142
368
  function itemRow(item: WixDataItem, collection: CmsCollectionDefinition, index: number): ItemRow {
143
369
  const data = item.data ?? {};
144
- const primary = displayValue(data[collection.displayField], collection.fields.find((field) => field.key === collection.displayField)?.type);
145
- // A RICH_CONTENT field renders as the row's document, never as a detail line.
146
- const details = collection.fields
147
- .filter((field) => field.key !== collection.displayField && !field.type.includes("IMAGE") && !field.type.includes("RICH_CONTENT"))
148
- .map((field) => ({ label: field.displayName, value: displayValue(data[field.key], field.type) }))
149
- .filter((entry) => entry.value)
150
- .slice(0, 2);
370
+ const fieldOf = (key: string) => collection.fields.find((field) => field.key === key);
371
+ const primary = displayValue(data[collection.displayField], fieldOf(collection.displayField)?.type);
151
372
  const title = primary || copyTemplate("cmsCollection.itemFallbackTitle", "Item {n}", { n: index + 1 });
152
- const image = imageValue(data, collection.fields);
373
+ // A RICH_CONTENT field renders as the row's document, never as a text line.
374
+ const texts = collection.fields.filter((field) => field.key !== collection.displayField && field.type.includes("TEXT") && !field.type.includes("RICH_CONTENT"));
375
+ const summary = texts[0] ? displayValue(data[texts[0].key], texts[0].type) : "";
376
+ // The meta line states only what the item holds: its date, then a second text field short enough to be a label.
377
+ const dateField = collection.fields.find((field) => field.key !== collection.displayField && field.type.includes("DATE"));
378
+ const date = dateField ? displayValue(data[dateField.key], dateField.type) : "";
379
+ const second = texts[1] ? displayValue(data[texts[1].key], texts[1].type) : "";
380
+ const meta = [date, second.length > 0 && second.length <= META_FIELD_MAX_CHARS ? second : ""].filter(Boolean).join(" · ");
153
381
  const rich = collection.fields.find((field) => field.type.includes("RICH_CONTENT"));
154
382
  const { bodyJson, bodyText } = richBody(rich ? data[rich.key] : null, "", ROW_IMAGE_WIDTH);
155
- return {
383
+ return finishRow({
156
384
  id: item.id || String(data._id ?? `${collection.id}-${index}`),
157
385
  title,
158
- subtitle: details[0] ? `${details[0].label}: ${details[0].value}` : "",
159
- meta: details[1] ? `${details[1].label}: ${details[1].value}` : "",
160
- image,
161
- initial: (title[0] || "C").toUpperCase(),
162
- hasImage: Boolean(image),
163
- noImage: !image,
386
+ fallbackIndex: primary ? undefined : index + 1,
387
+ primaryDate: fieldOf(collection.displayField)?.type.includes("DATE") ? rawDate(data[collection.displayField]) : undefined,
388
+ metaDate: dateField ? rawDate(data[dateField.key]) : "",
389
+ metaSuffix: second.length <= META_FIELD_MAX_CHARS ? second : "",
390
+ summary,
391
+ meta,
392
+ image: imageValue(data, collection.fields),
164
393
  bodyJson,
165
- hasBodyJson: bodyJson !== "",
166
394
  bodyText,
167
- };
168
- }
169
-
170
- function ready(collection: CmsCollectionDefinition, all: ItemRow[], rows = all, emptyText = copyParam("cmsCollection.emptyText", "This collection has no published items yet.")): State {
171
- return {
172
- status: "ready",
173
- collectionName: collection.displayName,
174
- collectionId: collection.id,
175
- accessLabel: collection.readRole === "ANYONE"
176
- ? copyParam("cmsCollection.visitorAccessLabel", "Visible to visitors")
177
- : copyParam("cmsCollection.membersAccessLabel", "Visible to signed-in members"),
178
- all,
179
- rows,
180
- emptyText,
181
- errorText: "",
182
- isLoading: false,
183
- notLoading: true,
184
- isErrored: false,
185
- notErrored: true,
186
- noRows: rows.length === 0,
187
- noEmpty: rows.length > 0,
188
- };
395
+ }, collection);
189
396
  }
190
397
 
191
398
  function argValue(arg: unknown, key: string): string {
@@ -229,81 +436,263 @@ function resolveCollection(arg: unknown): CmsCollectionDefinition | undefined {
229
436
  return id ? list.find((candidate) => candidate.id === id) : undefined;
230
437
  }
231
438
 
232
- // The in-flight load, keyed by collection. A second load() for the same collection JOINS it and
233
- // resolves to its result — it must not return the stale `loading` state it was handed, because the
234
- // module-scope boot load starts first and the host's onAppear load (what `himi render --live`
235
- // awaits before reading state) arrives while it is still running.
236
- let inflight: { id: string; promise: Promise<State> } | null = null;
439
+ /** One verdict per failure, so each failure has exactly one node. The message of the error is never shown.
440
+ * A member-only collection read as a guest answers 403 WDE0027: that is a sign-in, not a permission. */
441
+ function classify(error: unknown, collection: CmsCollectionDefinition): ErrorKind {
442
+ const text = String(error);
443
+ const status = /HTTP\s*(\d{3})/i.exec(text)?.[1] ?? "";
444
+ if (status === "401" || /unauthori[sz]ed|unauthenticated/i.test(text)) return "signIn";
445
+ if (status === "403" || /WDE0027|forbidden|permission denied/i.test(text)) return collection.readRole !== "ANYONE" ? "signIn" : "permission";
446
+ return status ? "server" : "offline";
447
+ }
448
+
449
+ function countLine(total: number): string {
450
+ return copyTemplate(total === 1 ? "cmsCollection.countOne" : "cmsCollection.countMany", total === 1 ? "{count} item" : "{count} items", { count: total });
451
+ }
452
+
453
+ let current: CmsCollectionDefinition | undefined;
454
+ let firstPageFlight: { collectionId: string; promise: Promise<State> } | undefined;
455
+ const WARM_FRESH_MS = 30_000;
456
+ let loadingMoreFlight: { cursor: string; generation: number } | undefined;
457
+ let firstPageGeneration = 0;
458
+ /** The latest state, so a read in flight can repaint (the load-more spinner) before its action returns. */
459
+ let published: State | undefined;
460
+
461
+ async function denyAccess(collection: CmsCollectionDefinition, errorKind: ErrorKind): Promise<State> {
462
+ // Access denial supersedes both in-memory rows and their offline snapshot.
463
+ // Retire pending pages/counts before awaiting native storage acknowledgements.
464
+ ++firstPageGeneration;
465
+ const fence = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
466
+ // Dispatch the durable fence before publishing denial, independently of an old
467
+ // snapshot acknowledgement. Other workers never trust a snapshot with an older fence.
468
+ const fenced = upsert(ENTITY, { id: accessKey(collection.id), cachePageKind: "cms-revocation", cachePageVersion: 1, cacheAccessFence: fence, rowsJson: "[]" }).catch(() => {});
469
+ // Queue the empty replacement at the database now, not after an old worker's
470
+ // acknowledgement: that older callback must not erase a newer authorized worker.
471
+ const cleared = upsert(ENTITY, { id: pageCacheKey(collection.id), cachePageKind: "cms-first-page", cachePageVersion: 1, cacheAccessFence: fence, rowsJson: "[]" }).catch(() => {});
472
+ cacheWriteTail = Promise.all([cacheWriteTail, fenced, cleared]).then(() => {});
473
+ const denied = derive(facts(collection, { status: "error", errorKind, countPending: false, cacheAccessFence: fence }));
474
+ published = denied;
475
+ void svc.publish();
476
+ await cacheWriteTail;
477
+ return published ?? denied;
478
+ }
479
+
480
+ /** The title and the media slot are known before any request: the first frame is the final title and a skeleton. */
481
+ const boot = resolveCollection(undefined);
482
+
483
+ function loadFirstPage(state: State, arg?: unknown): Promise<State> {
484
+ stashCopy(arg);
485
+ const collection = resolveCollection(arg);
486
+ if (argValue(arg, "force") !== "1" && collection && firstPageFlight?.collectionId === collection.id) {
487
+ if (published?.collectionId === collection.id) {
488
+ published = localizeState(published);
489
+ void svc.publish();
490
+ }
491
+ return firstPageFlight.promise;
492
+ }
493
+ const promise = readFirstPage(state, arg).then(localizeState);
494
+ const flight = { collectionId: collection?.id ?? "", promise };
495
+ firstPageFlight = flight;
496
+ void promise.finally(() => { if (firstPageFlight === flight) firstPageFlight = undefined; });
497
+ return promise;
498
+ }
499
+
500
+ async function readFirstPage(state: State, arg?: unknown): Promise<State> {
501
+ stashCopy(arg);
502
+ const collection = resolveCollection(arg);
503
+ if (!collection) {
504
+ current = undefined;
505
+ ++firstPageGeneration;
506
+ return published = derive(facts(undefined, { status: "error", countPending: false, errorKind: "server" }));
507
+ }
508
+ // Queued loads/retries can carry a snapshot from before a page or toggle.
509
+ // Adopt only the resolved collection's latest presentation before freshness/retention decisions.
510
+ if (published?.collectionId === collection.id) state = published;
511
+ // A cold-restored ready state skips the first read but still needs its paging definition.
512
+ current = collection;
513
+ const force = argValue(arg, "force") === "1";
514
+ const fresh = !force && state.collectionId === collection.id && state.status === "ready" && Date.now() - state.lastSuccessAt < WARM_FRESH_MS;
515
+ // A forced/stale refresh retires old pages before the asynchronous fence read.
516
+ const refreshGeneration = fresh ? undefined : ++firstPageGeneration;
517
+ if (!fresh && state.collectionId === collection.id && state.status === "ready") {
518
+ published = derive({ ...state, refreshing: true, loadingMore: false });
519
+ void svc.publish();
520
+ }
521
+ let revoked = false;
522
+ if (state.collectionId === collection.id && state.status === "ready") {
523
+ const generationBeforeFence = firstPageGeneration;
524
+ const fence = await readAccessFence(collection.id);
525
+ if (generationBeforeFence !== firstPageGeneration || current?.id !== collection.id) return published ?? state;
526
+ if (published?.collectionId === collection.id) state = published;
527
+ revoked = fence !== undefined && (state.cacheAccessFence ?? "") !== fence;
528
+ if (revoked) state = derive(facts(collection));
529
+ else if (fresh) return published = state;
530
+ }
531
+ const generation = refreshGeneration ?? ++firstPageGeneration;
532
+ // A different collection owns a different cursor and row actions. Retire the
533
+ // previous presentation before even the asynchronous local-cache read.
534
+ if (state.collectionId !== collection.id || revoked) {
535
+ published = derive(facts(collection));
536
+ void svc.publish();
537
+ }
538
+ const keptRows = state.collectionId === collection.id && state.status === "ready" ? state.rows : [];
539
+ // Last-synced items for THIS collection (offline-safe; empty on first-ever run).
540
+ const cache = keptRows.length ? { rows: [], accessFence: state.cacheAccessFence ?? "" } : await readCached(collection.id, collection);
541
+ const cached = cache.rows;
542
+ if (generation !== firstPageGeneration) return published ?? state;
543
+ const base = facts(collection, { cacheAccessFence: cache.accessFence ?? "" });
544
+ // A cold cache is usable while a slow request is still pending; warm rows stay exactly as shown.
545
+ const retained = keptRows.length ? derive({ ...state, refreshing: true, loadingMore: false }) : cached.length ? derive({ ...base, status: "ready", rows: cached, refreshing: true }) : undefined;
546
+ if (retained) {
547
+ published = retained;
548
+ void svc.publish();
549
+ }
550
+ // The count never blocks the rows and never shows an error: a failed count shows no caption.
551
+ let countPending = true;
552
+ let countTotal: number | null = null;
553
+ let rowsPublished = !!retained;
554
+ void countDataItems(collection.id)
555
+ .then((result) => (typeof result.totalCount === "number" && Number.isFinite(result.totalCount) && result.totalCount >= 0 ? result.totalCount : null))
556
+ .catch(() => null)
557
+ .then((total) => {
558
+ countPending = false;
559
+ countTotal = total;
560
+ // Counts settle independently. Merge into the latest rows so an expansion or page
561
+ // arriving meanwhile is retained, and ignore counts from a superseded refresh.
562
+ if (rowsPublished && generation === firstPageGeneration && published?.status === "ready") {
563
+ const preserve = published.refreshing || published.refreshFailed;
564
+ published = derive({ ...published,
565
+ countTotal: total ?? (preserve ? published.countTotal : null),
566
+ countText: total === null && !preserve ? "" : published.countText,
567
+ countPending: false,
568
+ });
569
+ void svc.publish();
570
+ }
571
+ });
572
+ try {
573
+ const response = await queryDataItems(collection.id, PAGE_SIZE, { sort: DEFAULT_SORT });
574
+ if (generation !== firstPageGeneration) return published ?? state;
575
+ const items = response.dataItems ?? response.items ?? [];
576
+ let rows = items.map((item, index) => itemRow(item, collection, index));
577
+ await writeCached(collection.id, rows, generation, cache.accessFence);
578
+ if (generation !== firstPageGeneration) return published ?? state;
579
+ // Read interaction state after storage too: a tap may happen while a local write awaits.
580
+ const previous = published?.collectionId === collection.id ? published : state.collectionId === collection.id ? state : undefined;
581
+ const expandedIds = new Set(previous?.rows.filter((row) => row.expanded).map((row) => row.id) ?? []);
582
+ if (expandedIds.size) rows = rows.map((row) => row.expandable && expandedIds.has(row.id) ? setRowExpanded(row, true) : row);
583
+ rowsPublished = true;
584
+ return published = derive({ ...base, status: "ready", rows, nextCursor: response.pagingMetadata?.cursors?.next ?? "", countTotal: countPending ? retained?.countTotal ?? null : countTotal, countText: countPending ? retained?.countText ?? "" : "", countPending, lastSuccessAt: Date.now() });
585
+ } catch (error) {
586
+ if (generation !== firstPageGeneration) return published ?? state;
587
+ const errorKind = classify(error, collection);
588
+ if (errorKind === "signIn" || errorKind === "permission") {
589
+ return denyAccess(collection, errorKind);
590
+ }
591
+ const retainedState = retained ? published ?? retained : undefined;
592
+ // Only transport/server failures preserve rows and interactions while offline.
593
+ if (retainedState?.rows.length) {
594
+ rowsPublished = true;
595
+ return published = derive({ ...retainedState, status: "ready", refreshFailed: true, refreshing: false,
596
+ countTotal: countTotal ?? retainedState.countTotal, countText: retainedState.countText, countPending: countPending && !retainedState.countText });
597
+ }
598
+ return published = derive({ ...base, status: "error", errorKind, countPending: false });
599
+ }
600
+ }
601
+
602
+ const initialState = derive(facts(boot));
603
+ // Every domain fact/flag belongs to this run or the bounded cms_items snapshot.
604
+ // The decorator's row projection must not become a second generic disk cache;
605
+ // its small preferences remain governed by localPreferences independently.
606
+ const cacheOwnedKeys = [...Object.keys(initialState), "collection"] as (keyof State & string)[];
237
607
 
238
608
  const svc = defineService<State, {
239
609
  load: (state: State, arg?: unknown) => Promise<State>;
240
- search: (state: State, arg?: unknown) => State;
610
+ retry: (state: State, arg?: unknown) => Promise<State>;
611
+ loadMore: (state: State, arg?: unknown) => Promise<State>;
612
+ toggleRow: (state: State, arg?: unknown) => State;
613
+ publish: (state: State) => State;
241
614
  /** [rico] #3372 — a row RichContent's on_link: `{ url }` of the tapped link. */
242
615
  openLink: (state: State, arg?: unknown) => Promise<State>;
243
616
  }>("himiBrandedCmsCollection", {
244
- state: initial,
617
+ state: initialState,
618
+ notHydrated: cacheOwnedKeys,
619
+ notPersisted: cacheOwnedKeys,
245
620
  actions: {
246
- load: async (state, arg) => {
247
- stashCopy(arg);
248
- const collection = resolveCollection(arg);
249
- if (!collection) return { ...state, status: "error", isLoading: false, notLoading: true, isErrored: true, notErrored: false, errorText: copyParam("cmsCollection.notConfiguredError", "This collection is not configured for the app.") };
250
- const force = argValue(arg, "force") === "1";
251
- if (!force && state.collectionId === collection.id && state.status === "ready") return state;
252
- if (!force && inflight && inflight.id === collection.id) return inflight.promise;
253
- const run = (async (): Promise<State> => {
254
- // Last-synced items for THIS collection (offline-safe; empty on first-ever run).
255
- const cached = await readCached(collection.id);
621
+ load: loadFirstPage,
622
+ // The error node's, the banner's and the sign-in return's "Try again": the same first load, forced.
623
+ retry: (state, arg) => loadFirstPage(state, { ...(typeof arg === "object" && arg ? arg as Record<string, unknown> : {}), force: "1" }),
624
+ loadMore: async (state) => {
625
+ const collection = current;
626
+ if (!collection || state.collectionId !== collection.id) return published ?? state;
627
+ // A queued action may carry the pre-refresh cursor. Keep the incoming
628
+ // collection fence, then use the presentation the refresh actually owns.
629
+ const active = published ?? state;
630
+ const cursor = active.nextCursor;
631
+ if (active.collectionId !== collection.id || active.status !== "ready" || active.refreshing || !cursor) return active;
632
+ const generation = firstPageGeneration;
633
+ if (loadingMoreFlight?.cursor === cursor && loadingMoreFlight.generation === generation) return active;
634
+ const flight = { cursor, generation };
635
+ loadingMoreFlight = flight;
636
+ published = derive({ ...active, loadingMore: true, pageError: false });
637
+ void svc.publish();
256
638
  try {
257
- const response = await queryDataItems(collection.id);
639
+ // The cursor already carries the sort (and later the filter): they are not sent again.
640
+ const response = await queryDataItems(collection.id, PAGE_SIZE, { cursor });
641
+ if (generation !== firstPageGeneration) return published ?? state;
642
+ const latest = published ?? state;
258
643
  const items = response.dataItems ?? response.items ?? [];
259
- const all = items.map((item, index) => itemRow(item, collection, index));
260
- await writeCached(collection.id, all);
261
- return ready(collection, all);
262
- } catch {
263
- // Offline / fetch failure: keep the cached items instead of a blank error state.
264
- if (cached.length) return ready(collection, cached);
265
- return {
266
- ...state,
267
- status: "error",
268
- collectionName: collection.displayName,
269
- collectionId: collection.id,
270
- accessLabel: collection.readRole === "ANYONE"
271
- ? copyParam("cmsCollection.visitorAccessLabel", "Visible to visitors")
272
- : copyParam("cmsCollection.membersOnlyAccessLabel", "Members only"),
273
- isLoading: false,
274
- notLoading: true,
275
- isErrored: true,
276
- notErrored: false,
277
- noEmpty: true,
278
- // Both member-gated reads want the sign-in hint, not "temporarily unavailable":
279
- // SITE_MEMBER needs *a* member, SITE_MEMBER_AUTHOR needs the member who authored
280
- // the rows. Only a genuinely unexpected role is an outage.
281
- errorText: collection.readRole === "SITE_MEMBER" || collection.readRole === "SITE_MEMBER_AUTHOR"
282
- ? copyParam("cmsCollection.memberSignInError", "Sign in from Profile to view this member collection.")
283
- : copyParam("cmsCollection.unavailableError", "This collection is temporarily unavailable."),
284
- };
644
+ const seen = new Set(latest.rows.map((row) => row.id));
645
+ const more: ItemRow[] = [];
646
+ for (const item of items) {
647
+ const row = itemRow(item, collection, latest.rows.length + more.length);
648
+ if (seen.has(row.id)) continue;
649
+ seen.add(row.id);
650
+ more.push(row);
651
+ }
652
+ published = derive({ ...latest, rows: [...latest.rows, ...more], nextCursor: response.pagingMetadata?.cursors?.next ?? "", loadingMore: false, pageError: false });
653
+ // A fresh warm load can supersede this action in the collection decorator
654
+ // without starting a new read. Commit through the current service too.
655
+ void svc.publish();
656
+ return published;
657
+ } catch (error) {
658
+ if (generation !== firstPageGeneration) return published ?? state;
659
+ const errorKind = classify(error, collection);
660
+ if (errorKind === "signIn" || errorKind === "permission") return denyAccess(collection, errorKind);
661
+ // Transport/server failures keep rows; the end marker retries this cursor.
662
+ published = derive({ ...(published ?? state), loadingMore: false, pageError: true });
663
+ void svc.publish();
664
+ return published;
665
+ } finally {
666
+ if (loadingMoreFlight === flight) loadingMoreFlight = undefined;
285
667
  }
286
- })();
287
- const entry = { id: collection.id, promise: run };
288
- inflight = entry;
289
- try { return await run; } finally { if (inflight === entry) inflight = null; }
290
668
  },
291
- search: (state, arg) => {
292
- const query = argValue(arg, "value").trim().toLowerCase();
293
- const rows = query
294
- ? state.all.filter((row) => `${row.title} ${row.subtitle} ${row.meta}`.toLowerCase().includes(query))
295
- : state.all;
296
- return { ...state, rows, noRows: rows.length === 0, noEmpty: rows.length > 0, emptyText: query ? copyParam("cmsCollection.searchEmptyText", "No items match your search.") : copyParam("cmsCollection.emptyText", "This collection has no published items yet.") };
669
+ toggleRow: (state, arg) => {
670
+ if (!current || state.collectionId !== current.id) return published ?? state;
671
+ const active = published ?? state;
672
+ const id = argValue(arg, "id");
673
+ if (active.collectionId !== current.id || !active.rows.some((row) => row.id === id && row.expandable)) return active;
674
+ const rows = active.rows.map((row) => row.id === id && row.expandable ? setRowExpanded(row, !row.expanded) : row);
675
+ return published = derive({ ...active, rows });
297
676
  },
677
+ publish: (state) => published ?? state,
298
678
  // Only http(s), mailto and tel links reach open_url; the collection has no message line, so a refused
299
679
  // link simply does nothing.
300
680
  openLink: async (state, arg) => {
301
681
  await openRichLink(arg);
302
- return state;
682
+ return published ?? state;
303
683
  },
304
684
  },
305
685
  });
306
686
 
687
+ // Shipped runtimes before hydration opt-out support overlay their generic snapshot at registration.
688
+ // Reset this boot's facts and decorator projection in place before load's freshness guard can run.
689
+ // Recomputing the projection keeps independently stored collection preferences, never snapshot UI.
690
+ if ((globalThis as { himalaya?: { hydrationOptOut?: unknown } }).himalaya?.hydrationOptOut !== true) {
691
+ const live = (svc as { getState?: () => State | undefined }).getState?.();
692
+ if (live && typeof live === "object") Object.assign(live,
693
+ decorateCollection("himiBrandedCmsCollection", { state: { ...initialState } }).state);
694
+ }
695
+
307
696
  // Cold-seed boot: exact bakes carry the single `collection`, the canonical
308
697
  // shell carries the `collections` list (+ id nav param) — both start loading
309
698
  // immediately; onAppear's load dedupes via the collectionId/status guards.