| 1 | /** Preserve transcript on failed hydrate instead of painting a successful empty session. */ |
| 2 | export function applyHydrateErrorState< |
| 3 | TItem, |
| 4 | S extends { |
| 5 | items: TItem[]; |
| 6 | hydratePlaceholderItems?: TItem[]; |
| 7 | hydrateHistoryLoaded?: boolean; |
| 8 | }, |
| 9 | >(s: S, reason: string, error: string): S & { |
| 10 | hydrating: false; |
| 11 | hydrateReason: string; |
| 12 | hydrateError: string; |
| 13 | hydrateHistoryLoaded?: boolean; |
| 14 | hydratePlaceholderItems: undefined; |
| 15 | } { |
| 16 | const keptItems = s.items.length > 0 |
| 17 | ? s.items |
| 18 | : (s.hydratePlaceholderItems?.length ? s.hydratePlaceholderItems : s.items); |
| 19 | return { |
| 20 | ...s, |
| 21 | items: keptItems, |
| 22 | hydrating: false, |
| 23 | hydrateReason: reason, |
| 24 | hydrateError: error, |
| 25 | hydrateHistoryLoaded: s.hydrateHistoryLoaded || keptItems.length > 0 || undefined, |
| 26 | hydratePlaceholderItems: undefined, |
| 27 | }; |
| 28 | } |
| 29 | |
| 30 | /** The recovery detail for a failed history read: the summary, then the reader's own identity and cause. */ |
| 31 | export function hydrateFailureDetail(summary: string, cause: unknown): string { |
| 32 | const message = (cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "").trim(); |
| 33 | const failure = cause as { stage?: unknown; reason?: unknown } | undefined; |
| 34 | const identity = cause instanceof Error && typeof failure?.stage === "string" && typeof failure.reason === "string" |
| 35 | ? `${failure.stage}.${failure.reason}` : ""; |
| 36 | const line = [identity, message].filter(Boolean).join(": "); |
| 37 | return line ? `${summary}\n${line}` : summary; |
| 38 | } |
| 39 | |
| 40 | export function hydratePlaceholderItems<TItem>( |
| 41 | optionsItems: TItem[] | undefined, |
| 42 | ): TItem[] | undefined { |
| 43 | return optionsItems?.length ? optionsItems : undefined; |
| 44 | } |
| 45 |