@fifthbell/brokaw 0.1.70 → 0.1.73

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 (59) hide show
  1. package/README.md +112 -0
  2. package/dist/captured-catalog-browser.d.ts +26 -0
  3. package/dist/captured-catalog-browser.js +42 -0
  4. package/dist/captured-catalog-reader.d.ts +16 -0
  5. package/dist/captured-catalog-reader.js +113 -0
  6. package/dist/captured-catalog.d.ts +28 -0
  7. package/dist/captured-catalog.js +124 -0
  8. package/dist/components/live-program/LiveProgram.js +119 -311
  9. package/dist/components/live-program/components/WorldClocks.js +2 -1
  10. package/dist/components/live-program/components/slides/LiveEventSlide.js +2 -4
  11. package/dist/components/live-program/events.d.ts +7 -0
  12. package/dist/components/live-program/events.js +28 -5
  13. package/dist/components/live-program/hooks/useSSE.js +1 -2
  14. package/dist/components/live-program/i18n.js +1 -1
  15. package/dist/components/live-program/live-program-config.d.ts +70 -0
  16. package/dist/components/live-program/live-program-config.js +228 -0
  17. package/dist/components/live-program/program-data.d.ts +22 -0
  18. package/dist/components/live-program/program-data.js +23 -0
  19. package/dist/components/live-program/program-reload.d.ts +11 -0
  20. package/dist/components/live-program/program-reload.js +21 -0
  21. package/dist/components/live-program/segments/ArticlesSegment.d.ts +5 -0
  22. package/dist/components/live-program/segments/ArticlesSegment.js +15 -11
  23. package/dist/components/live-program/segments/EarthquakeSegment.d.ts +4 -0
  24. package/dist/components/live-program/segments/EarthquakeSegment.js +13 -10
  25. package/dist/components/live-program/segments/MarketsSegment.js +7 -2
  26. package/dist/components/live-program/segments/WeatherSegment.d.ts +5 -0
  27. package/dist/components/live-program/segments/WeatherSegment.js +7 -2
  28. package/dist/components/live-program/segments/fetchLiveEvents.d.ts +6 -0
  29. package/dist/components/live-program/segments/fetchLiveEvents.js +42 -27
  30. package/dist/components/live-program/source-retention.d.ts +14 -0
  31. package/dist/components/live-program/source-retention.js +26 -0
  32. package/dist/cronkite-manifest.d.ts +35 -0
  33. package/dist/cronkite-manifest.js +5 -26
  34. package/dist/cronkite-manifest.json +48 -1
  35. package/dist/layouts.d.ts +1 -1
  36. package/dist/live-program-page/index.html +2 -2
  37. package/dist/live-program-page/live-program-manifest.json +8 -8
  38. package/dist/live-program-page/live-program.v0.1.73.css +3 -0
  39. package/dist/live-program-page/live-program.v0.1.73.js +76 -0
  40. package/dist/manifest-validation.js +3 -1
  41. package/dist/renderer.browser.js +2 -0
  42. package/dist/renderer.core.js +3 -7
  43. package/dist/schemas/canonical-document.schema.json +69 -1
  44. package/dist/system-pages.d.ts +66 -0
  45. package/dist/system-pages.js +35 -0
  46. package/dist/types/canonical-article.js +3 -2
  47. package/dist/types/canonical-document-schema.generated.d.ts +132 -0
  48. package/dist/types/canonical-document-schema.generated.js +146 -0
  49. package/dist/types/canonical-document.generated.d.ts +34 -0
  50. package/package.json +10 -4
  51. package/src/partial-deps.json +9 -0
  52. package/src/styles/compiled.css +1 -1
  53. package/src/templates/partials/components/article-main.hbs +6 -5
  54. package/src/templates/partials/components/media/main.hbs +4 -3
  55. package/src/templates/partials/components/search/main.hbs +3 -3
  56. package/src/templates/partials/headers/header-main.hbs +11 -19
  57. package/src/templates/partials/shell/captured-catalog.hbs +1 -0
  58. package/dist/live-program-page/live-program.v0.1.70.css +0 -3
  59. package/dist/live-program-page/live-program.v0.1.70.js +0 -76
@@ -1,3 +1,4 @@
1
+ import { SOURCE_RETENTION_MS } from './source-retention.js';
1
2
  const SUPPORTED_LANGUAGE_SET = new Set(['en', 'es', 'it']);
2
3
  const eventCacheByKey = new Map();
3
4
  let activeCacheKey = '__default__';
@@ -61,10 +62,13 @@ function buildCacheKey(language, allowedLanguages) {
61
62
  const allowedPart = allowedLanguages.length > 0 ? [...allowedLanguages].sort().join(',') : 'all';
62
63
  return `${languagePart}__${allowedPart}`;
63
64
  }
65
+ function cacheKeyFor(options) {
66
+ return buildCacheKey(normalizeLanguageToken(options.language) ?? undefined, normalizeAllowedLanguages(options.allowedLanguages));
67
+ }
64
68
  export async function fetchEvents(options = {}) {
65
69
  const allowedLanguages = normalizeAllowedLanguages(options.allowedLanguages);
66
70
  const preferredLanguage = normalizeLanguageToken(options.language);
67
- const cacheKey = buildCacheKey(preferredLanguage ?? undefined, allowedLanguages);
71
+ const cacheKey = cacheKeyFor(options);
68
72
  const eventsApiUrl = new URL('https://api.monitor.gaulatti.com/events');
69
73
  if (preferredLanguage) {
70
74
  eventsApiUrl.searchParams.set('language', preferredLanguage);
@@ -119,6 +123,27 @@ export async function fetchEvents(options = {}) {
119
123
  activeCacheKey = cacheKey;
120
124
  return nextEvents;
121
125
  }
126
+ /**
127
+ * fetchEvents that never throws (fifthbell/brokaw#35). When the events service
128
+ * fails, the last good events for the same options stay for up to
129
+ * SOURCE_RETENTION_MS after their fetch; older ones are dropped, and an empty
130
+ * list is returned so the program runs without event segments.
131
+ */
132
+ export async function fetchEventsRetained(options = {}) {
133
+ try {
134
+ return await fetchEvents(options);
135
+ }
136
+ catch (error) {
137
+ console.warn('[live-program] events unavailable', error);
138
+ const cacheKey = cacheKeyFor(options);
139
+ const lastGood = eventCacheByKey.get(cacheKey);
140
+ if (lastGood && Date.now() - lastGood.lastFetchTime.getTime() <= SOURCE_RETENTION_MS) {
141
+ return lastGood.events;
142
+ }
143
+ eventCacheByKey.delete(cacheKey);
144
+ return [];
145
+ }
146
+ }
122
147
  export function getCachedEvents() {
123
148
  return eventCacheByKey.get(activeCacheKey)?.events ?? null;
124
149
  }
@@ -147,9 +172,6 @@ export function hasEventChanges(oldEvents, newEvents) {
147
172
  }
148
173
  for (const [uuid, newEvent] of newMap.entries()) {
149
174
  const oldEvent = oldMap.get(uuid);
150
- if (!oldEvent) {
151
- continue;
152
- }
153
175
  if (oldEvent.title !== newEvent.title ||
154
176
  oldEvent.status !== newEvent.status ||
155
177
  oldEvent.posts_count !== newEvent.posts_count ||
@@ -158,7 +180,8 @@ export function hasEventChanges(oldEvents, newEvents) {
158
180
  }
159
181
  const oldPostMap = new Map(oldEvent.posts.map((post) => [post.uuid, post]));
160
182
  for (const post of newEvent.posts) {
161
- if (!oldPostMap.has(post.uuid)) {
183
+ const oldPost = oldPostMap.get(post.uuid);
184
+ if (!oldPost || oldPost.relevance !== post.relevance) {
162
185
  return true;
163
186
  }
164
187
  }
@@ -46,9 +46,8 @@ export function useSSE({ url, onMessage, onOpen, onDiagnostic, reconnectInterval
46
46
  processLine(trimmed);
47
47
  }
48
48
  };
49
+ // Only the mount and the reconnect timer call connect; cleanup clears that timer.
49
50
  const connect = async () => {
50
- if (disposed)
51
- return;
52
51
  try {
53
52
  abortController = new AbortController();
54
53
  bufferRef.current = '';
@@ -291,7 +291,7 @@ export function t(key, language, replacements) {
291
291
  console.warn(`Translation missing for key: ${key}`);
292
292
  return key;
293
293
  }
294
- let text = translation[language] || translation.en || key;
294
+ let text = translation[language] || translation.en;
295
295
  if (replacements) {
296
296
  Object.entries(replacements).forEach(([placeholder, value]) => {
297
297
  text = text.replace(`{${placeholder}}`, String(value));
@@ -0,0 +1,70 @@
1
+ import { type SupportedLanguage } from './i18n.js';
2
+ export interface Layout {
3
+ id: number;
4
+ name: string;
5
+ componentType: string;
6
+ settings: string;
7
+ }
8
+ export interface Scene {
9
+ id: number;
10
+ name: string;
11
+ layoutId: number;
12
+ layout: Layout;
13
+ chyronText: string | null;
14
+ metadata: string | null;
15
+ }
16
+ export interface FifthBellWorldClockCity {
17
+ city: string;
18
+ timezone: string;
19
+ }
20
+ export interface FifthBellConfig {
21
+ showArticles: boolean;
22
+ showWeather: boolean;
23
+ showEarthquakes: boolean;
24
+ showMarkets: boolean;
25
+ showLiveEvents: boolean;
26
+ showMarquee: boolean;
27
+ showCallsignTake: boolean;
28
+ weatherCities: string[];
29
+ languageRotation: SupportedLanguage[];
30
+ dataLoadTimeoutMs: number;
31
+ playlistDefaultDurationMs: number;
32
+ playlistUpdateIntervalMs: number;
33
+ articlesDurationMs: number;
34
+ weatherDurationMs: number;
35
+ earthquakesDurationMs: number;
36
+ marketsDurationMs: number;
37
+ showWorldClocks: boolean;
38
+ showBellIcon: boolean;
39
+ worldClockRotateIntervalMs: number;
40
+ worldClockTransitionMs: number;
41
+ worldClockShuffle: boolean;
42
+ worldClockWidthPx: number;
43
+ worldClockCities: FifthBellWorldClockCity[];
44
+ audioCueEnabled: boolean;
45
+ audioCueMinute: number;
46
+ audioCueSecond: number;
47
+ callsignPrelaunchUntilNyc: string;
48
+ callsignWindowStartSecond: number;
49
+ callsignWindowEndSecond: number;
50
+ marqueeMinPostsCount: number;
51
+ marqueeMinAverageRelevance: number;
52
+ marqueeMinMedianRelevance: number;
53
+ marqueePixelsPerSecond: number;
54
+ marqueeMinDurationSeconds: number;
55
+ marqueeHeightPx: number;
56
+ }
57
+ export declare function clampNumber(value: unknown, fallback: number, min: number, max: number): number;
58
+ export declare function normalizeBoolean(value: unknown, fallback: boolean): boolean;
59
+ export declare function normalizeStringArray(value: unknown): string[];
60
+ export declare function normalizeLanguageRotation(value: unknown): SupportedLanguage[];
61
+ export declare function normalizeWorldClockCities(value: unknown): FifthBellWorldClockCity[];
62
+ export declare function normalizeCityKey(value: string): string;
63
+ export declare function toRecord(value: unknown): Record<string, unknown>;
64
+ export declare function parseSceneMetadata(scene: Scene | null): Record<string, unknown>;
65
+ export declare function resolveFifthBellLayerAvailability(activeComponents?: string[]): {
66
+ content: boolean;
67
+ marquee: boolean;
68
+ };
69
+ export declare function extractConfigFromMetadata(metadataInput: Record<string, unknown> | null | undefined): FifthBellConfig;
70
+ export declare function normalizeLaunchDate(rawDate: string): Date;
@@ -0,0 +1,228 @@
1
+ // FifthBell scene configuration: how a scene's metadata becomes LiveProgram's
2
+ // settings. Internal to the live program; not part of the package exports.
3
+ import { DEFAULT_WORLD_CLOCK_CITIES } from './components/WorldClocks.js';
4
+ const DEFAULT_LANGUAGE_ROTATION = ['en', 'es', 'en', 'it'];
5
+ const DEFAULT_CALLSIGN_PRELAUNCH_UNTIL_NYC = '2026-01-02T21:30:00';
6
+ const FIFTHBELL_COMPONENT_TYPE_CONTENT = 'fifthbell-content';
7
+ const FIFTHBELL_COMPONENT_TYPE_MARQUEE = 'fifthbell-marquee';
8
+ const FIFTHBELL_COMPONENT_TYPE_TONI_CLOCK = 'toni-clock';
9
+ const FIFTHBELL_COMPONENT_TYPE_CORNER = 'fifthbell-corner';
10
+ const FIFTHBELL_COMPONENT_TYPE_LEGACY = 'fifthbell';
11
+ const DEFAULT_FIFTHBELL_CONFIG = {
12
+ showArticles: true,
13
+ showWeather: true,
14
+ showEarthquakes: true,
15
+ showMarkets: true,
16
+ showLiveEvents: true,
17
+ showMarquee: false,
18
+ showCallsignTake: true,
19
+ weatherCities: [],
20
+ languageRotation: DEFAULT_LANGUAGE_ROTATION,
21
+ dataLoadTimeoutMs: 15000,
22
+ playlistDefaultDurationMs: 10000,
23
+ playlistUpdateIntervalMs: 100,
24
+ articlesDurationMs: 10000,
25
+ weatherDurationMs: 5000,
26
+ earthquakesDurationMs: 10000,
27
+ marketsDurationMs: 10000,
28
+ showWorldClocks: true,
29
+ showBellIcon: true,
30
+ worldClockRotateIntervalMs: 7000,
31
+ worldClockTransitionMs: 300,
32
+ worldClockShuffle: true,
33
+ worldClockWidthPx: 200,
34
+ worldClockCities: [...DEFAULT_WORLD_CLOCK_CITIES],
35
+ audioCueEnabled: true,
36
+ audioCueMinute: 59,
37
+ audioCueSecond: 55,
38
+ callsignPrelaunchUntilNyc: DEFAULT_CALLSIGN_PRELAUNCH_UNTIL_NYC,
39
+ callsignWindowStartSecond: 50,
40
+ callsignWindowEndSecond: 3,
41
+ marqueeMinPostsCount: 4,
42
+ marqueeMinAverageRelevance: 0,
43
+ marqueeMinMedianRelevance: 0,
44
+ marqueePixelsPerSecond: 150,
45
+ marqueeMinDurationSeconds: 10,
46
+ marqueeHeightPx: 72
47
+ };
48
+ export function clampNumber(value, fallback, min, max) {
49
+ const numeric = typeof value === 'number' ? value : Number(value);
50
+ if (!Number.isFinite(numeric)) {
51
+ return fallback;
52
+ }
53
+ return Math.min(max, Math.max(min, numeric));
54
+ }
55
+ export function normalizeBoolean(value, fallback) {
56
+ if (typeof value === 'boolean') {
57
+ return value;
58
+ }
59
+ if (typeof value === 'number') {
60
+ return value !== 0;
61
+ }
62
+ if (typeof value === 'string') {
63
+ const normalized = value.trim().toLowerCase();
64
+ if (['true', '1', 'yes', 'on'].includes(normalized)) {
65
+ return true;
66
+ }
67
+ if (['false', '0', 'no', 'off', ''].includes(normalized)) {
68
+ return false;
69
+ }
70
+ }
71
+ return fallback;
72
+ }
73
+ export function normalizeStringArray(value) {
74
+ if (!Array.isArray(value)) {
75
+ return [];
76
+ }
77
+ const deduped = new Set();
78
+ for (const item of value) {
79
+ if (typeof item !== 'string') {
80
+ continue;
81
+ }
82
+ const trimmed = item.trim();
83
+ if (!trimmed) {
84
+ continue;
85
+ }
86
+ deduped.add(trimmed);
87
+ }
88
+ return [...deduped];
89
+ }
90
+ export function normalizeLanguageRotation(value) {
91
+ if (!Array.isArray(value)) {
92
+ return [...DEFAULT_LANGUAGE_ROTATION];
93
+ }
94
+ const allowed = new Set(['en', 'es', 'it']);
95
+ const filtered = value.filter((item) => typeof item === 'string' && allowed.has(item));
96
+ return filtered.length > 0 ? filtered : [...DEFAULT_LANGUAGE_ROTATION];
97
+ }
98
+ export function normalizeWorldClockCities(value) {
99
+ if (!Array.isArray(value)) {
100
+ return [...DEFAULT_WORLD_CLOCK_CITIES];
101
+ }
102
+ const normalized = value
103
+ .map((item) => {
104
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
105
+ return null;
106
+ }
107
+ const city = typeof item.city === 'string' ? item.city.trim() : '';
108
+ const timezone = typeof item.timezone === 'string' ? item.timezone.trim() : '';
109
+ if (!city || !timezone) {
110
+ return null;
111
+ }
112
+ return { city, timezone };
113
+ })
114
+ .filter((item) => item !== null);
115
+ return normalized.length > 0 ? normalized : [...DEFAULT_WORLD_CLOCK_CITIES];
116
+ }
117
+ export function normalizeCityKey(value) {
118
+ return value
119
+ .normalize('NFD')
120
+ .replace(/[\u0300-\u036f]/g, '')
121
+ .trim()
122
+ .toLowerCase();
123
+ }
124
+ export function toRecord(value) {
125
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
126
+ return value;
127
+ }
128
+ return {};
129
+ }
130
+ export function parseSceneMetadata(scene) {
131
+ if (!scene || !scene.metadata) {
132
+ return {};
133
+ }
134
+ try {
135
+ const parsed = JSON.parse(scene.metadata);
136
+ return toRecord(parsed);
137
+ }
138
+ catch {
139
+ return {};
140
+ }
141
+ }
142
+ export function resolveFifthBellLayerAvailability(activeComponents) {
143
+ const defaultAvailability = {
144
+ content: true,
145
+ marquee: true
146
+ };
147
+ if (!activeComponents || activeComponents.length === 0) {
148
+ return defaultAvailability;
149
+ }
150
+ if (activeComponents.includes(FIFTHBELL_COMPONENT_TYPE_LEGACY)) {
151
+ return defaultAvailability;
152
+ }
153
+ return {
154
+ content: activeComponents.includes(FIFTHBELL_COMPONENT_TYPE_CONTENT),
155
+ marquee: activeComponents.includes(FIFTHBELL_COMPONENT_TYPE_MARQUEE)
156
+ };
157
+ }
158
+ export function extractConfigFromMetadata(metadataInput) {
159
+ const metadata = toRecord(metadataInput);
160
+ const legacyProps = toRecord(metadata[FIFTHBELL_COMPONENT_TYPE_LEGACY]);
161
+ const contentProps = {
162
+ ...legacyProps,
163
+ ...toRecord(metadata[FIFTHBELL_COMPONENT_TYPE_CONTENT])
164
+ };
165
+ const marqueeProps = {
166
+ ...legacyProps,
167
+ ...toRecord(metadata[FIFTHBELL_COMPONENT_TYPE_MARQUEE])
168
+ };
169
+ const cornerProps = {
170
+ ...legacyProps,
171
+ ...toRecord(metadata[FIFTHBELL_COMPONENT_TYPE_TONI_CLOCK]),
172
+ ...toRecord(metadata[FIFTHBELL_COMPONENT_TYPE_CORNER])
173
+ };
174
+ const parsedMarqueeMinPostsCount = clampNumber(marqueeProps.marqueeMinPostsCount, DEFAULT_FIFTHBELL_CONFIG.marqueeMinPostsCount, 0, 50);
175
+ let parsedMarqueeMinAverageRelevance = clampNumber(marqueeProps.marqueeMinAverageRelevance, DEFAULT_FIFTHBELL_CONFIG.marqueeMinAverageRelevance, 0, 100);
176
+ let parsedMarqueeMinMedianRelevance = clampNumber(marqueeProps.marqueeMinMedianRelevance, DEFAULT_FIFTHBELL_CONFIG.marqueeMinMedianRelevance, 0, 100);
177
+ // Compatibility: prior defaults were tuned for OR logic. Under threshold logic, treat that trio as legacy.
178
+ if (parsedMarqueeMinPostsCount === 4 && parsedMarqueeMinAverageRelevance === 5 && parsedMarqueeMinMedianRelevance === 7) {
179
+ parsedMarqueeMinAverageRelevance = 0;
180
+ parsedMarqueeMinMedianRelevance = 0;
181
+ }
182
+ return {
183
+ showArticles: normalizeBoolean(contentProps.showArticles, DEFAULT_FIFTHBELL_CONFIG.showArticles),
184
+ showWeather: normalizeBoolean(contentProps.showWeather, DEFAULT_FIFTHBELL_CONFIG.showWeather),
185
+ showEarthquakes: normalizeBoolean(contentProps.showEarthquakes, DEFAULT_FIFTHBELL_CONFIG.showEarthquakes),
186
+ showMarkets: normalizeBoolean(contentProps.showMarkets, DEFAULT_FIFTHBELL_CONFIG.showMarkets),
187
+ showLiveEvents: normalizeBoolean(contentProps.showLiveEvents, DEFAULT_FIFTHBELL_CONFIG.showLiveEvents),
188
+ showMarquee: normalizeBoolean(marqueeProps.showMarquee, DEFAULT_FIFTHBELL_CONFIG.showMarquee),
189
+ showCallsignTake: normalizeBoolean(contentProps.showCallsignTake, DEFAULT_FIFTHBELL_CONFIG.showCallsignTake),
190
+ weatherCities: normalizeStringArray(contentProps.weatherCities),
191
+ languageRotation: normalizeLanguageRotation(contentProps.languageRotation),
192
+ dataLoadTimeoutMs: clampNumber(contentProps.dataLoadTimeoutMs, DEFAULT_FIFTHBELL_CONFIG.dataLoadTimeoutMs, 1000, 120000),
193
+ playlistDefaultDurationMs: clampNumber(contentProps.playlistDefaultDurationMs, DEFAULT_FIFTHBELL_CONFIG.playlistDefaultDurationMs, 1000, 120000),
194
+ playlistUpdateIntervalMs: clampNumber(contentProps.playlistUpdateIntervalMs, DEFAULT_FIFTHBELL_CONFIG.playlistUpdateIntervalMs, 16, 5000),
195
+ articlesDurationMs: clampNumber(contentProps.articlesDurationMs, DEFAULT_FIFTHBELL_CONFIG.articlesDurationMs, 1000, 120000),
196
+ weatherDurationMs: clampNumber(contentProps.weatherDurationMs, DEFAULT_FIFTHBELL_CONFIG.weatherDurationMs, 1000, 120000),
197
+ earthquakesDurationMs: clampNumber(contentProps.earthquakesDurationMs, DEFAULT_FIFTHBELL_CONFIG.earthquakesDurationMs, 1000, 120000),
198
+ marketsDurationMs: clampNumber(contentProps.marketsDurationMs, DEFAULT_FIFTHBELL_CONFIG.marketsDurationMs, 1000, 120000),
199
+ showWorldClocks: normalizeBoolean(cornerProps.showWorldClocks, DEFAULT_FIFTHBELL_CONFIG.showWorldClocks),
200
+ showBellIcon: true,
201
+ worldClockRotateIntervalMs: clampNumber(cornerProps.worldClockRotateIntervalMs, DEFAULT_FIFTHBELL_CONFIG.worldClockRotateIntervalMs, 500, 120000),
202
+ worldClockTransitionMs: clampNumber(cornerProps.worldClockTransitionMs, DEFAULT_FIFTHBELL_CONFIG.worldClockTransitionMs, 0, 10000),
203
+ worldClockShuffle: normalizeBoolean(cornerProps.worldClockShuffle, DEFAULT_FIFTHBELL_CONFIG.worldClockShuffle),
204
+ worldClockWidthPx: clampNumber(cornerProps.worldClockWidthPx, DEFAULT_FIFTHBELL_CONFIG.worldClockWidthPx, 120, 600),
205
+ worldClockCities: normalizeWorldClockCities(cornerProps.worldClockCities),
206
+ audioCueEnabled: normalizeBoolean(contentProps.audioCueEnabled, DEFAULT_FIFTHBELL_CONFIG.audioCueEnabled),
207
+ audioCueMinute: clampNumber(contentProps.audioCueMinute, DEFAULT_FIFTHBELL_CONFIG.audioCueMinute, 0, 59),
208
+ audioCueSecond: clampNumber(contentProps.audioCueSecond, DEFAULT_FIFTHBELL_CONFIG.audioCueSecond, 0, 59),
209
+ callsignPrelaunchUntilNyc: typeof contentProps.callsignPrelaunchUntilNyc === 'string' && contentProps.callsignPrelaunchUntilNyc.trim()
210
+ ? contentProps.callsignPrelaunchUntilNyc.trim()
211
+ : DEFAULT_FIFTHBELL_CONFIG.callsignPrelaunchUntilNyc,
212
+ callsignWindowStartSecond: clampNumber(contentProps.callsignWindowStartSecond, DEFAULT_FIFTHBELL_CONFIG.callsignWindowStartSecond, 0, 59),
213
+ callsignWindowEndSecond: clampNumber(contentProps.callsignWindowEndSecond, DEFAULT_FIFTHBELL_CONFIG.callsignWindowEndSecond, 0, 59),
214
+ marqueeMinPostsCount: parsedMarqueeMinPostsCount,
215
+ marqueeMinAverageRelevance: parsedMarqueeMinAverageRelevance,
216
+ marqueeMinMedianRelevance: parsedMarqueeMinMedianRelevance,
217
+ marqueePixelsPerSecond: clampNumber(marqueeProps.marqueePixelsPerSecond, DEFAULT_FIFTHBELL_CONFIG.marqueePixelsPerSecond, 10, 1000),
218
+ marqueeMinDurationSeconds: clampNumber(marqueeProps.marqueeMinDurationSeconds, DEFAULT_FIFTHBELL_CONFIG.marqueeMinDurationSeconds, 1, 120),
219
+ marqueeHeightPx: clampNumber(marqueeProps.marqueeHeightPx, DEFAULT_FIFTHBELL_CONFIG.marqueeHeightPx, 72, 200)
220
+ };
221
+ }
222
+ export function normalizeLaunchDate(rawDate) {
223
+ const parsed = new Date(rawDate);
224
+ if (Number.isNaN(parsed.getTime())) {
225
+ return new Date(DEFAULT_CALLSIGN_PRELAUNCH_UNTIL_NYC);
226
+ }
227
+ return parsed;
228
+ }
@@ -0,0 +1,22 @@
1
+ import { type Event } from './events.js';
2
+ import { type SupportedLanguage } from './i18n.js';
3
+ import { type NewsItem } from './segments/ArticlesSegment.js';
4
+ import { type EarthquakeData } from './segments/EarthquakeSegment.js';
5
+ import { type LiveEventData } from './segments/fetchLiveEvents.js';
6
+ import { type MarketData } from './segments/MarketsSegment.js';
7
+ import { type WeatherRegionData } from './segments/WeatherSegment.js';
8
+ export { SOURCE_RETENTION_MS } from './source-retention.js';
9
+ export interface ProgramData {
10
+ articles: NewsItem[];
11
+ weather: WeatherRegionData[];
12
+ earthquakes: EarthquakeData[];
13
+ markets: MarketData[];
14
+ liveEvent: LiveEventData | null;
15
+ events: Event[];
16
+ }
17
+ /**
18
+ * Loads every live-program source at once. No source can hold the others
19
+ * back: each one answers with its own fallback when it fails, and events keep
20
+ * their last good list for SOURCE_RETENTION_MS.
21
+ */
22
+ export declare function loadProgramData(language: SupportedLanguage): Promise<ProgramData>;
@@ -0,0 +1,23 @@
1
+ import { fetchEventsRetained } from './events.js';
2
+ import { fetchArticles } from './segments/ArticlesSegment.js';
3
+ import { fetchEarthquakes } from './segments/EarthquakeSegment.js';
4
+ import { fetchLiveEvent } from './segments/fetchLiveEvents.js';
5
+ import { fetchMarketData } from './segments/MarketsSegment.js';
6
+ import { fetchWeatherData } from './segments/WeatherSegment.js';
7
+ export { SOURCE_RETENTION_MS } from './source-retention.js';
8
+ /**
9
+ * Loads every live-program source at once. No source can hold the others
10
+ * back: each one answers with its own fallback when it fails, and events keep
11
+ * their last good list for SOURCE_RETENTION_MS.
12
+ */
13
+ export async function loadProgramData(language) {
14
+ const [articles, weather, earthquakes, markets, liveEvent, events] = await Promise.all([
15
+ fetchArticles(language),
16
+ fetchWeatherData(),
17
+ fetchEarthquakes(language),
18
+ fetchMarketData(),
19
+ fetchLiveEvent(language),
20
+ fetchEventsRetained({ language, allowedLanguages: [language] }),
21
+ ]);
22
+ return { articles, weather, earthquakes, markets, liveEvent, events };
23
+ }
@@ -0,0 +1,11 @@
1
+ /** The parts of the browser window a program reload uses. */
2
+ export interface ReloadWindow {
3
+ location: Pick<Location, 'href' | 'replace'>;
4
+ caches?: Pick<CacheStorage, 'keys' | 'delete'>;
5
+ }
6
+ /**
7
+ * Answers a program_reload event: clears every Cache Storage entry when the
8
+ * browser has Cache Storage, then reloads the page with a cache-busting query.
9
+ * A failed cache clear is reported and the page still reloads.
10
+ */
11
+ export declare function clearCachesAndReload(win: ReloadWindow): void;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Answers a program_reload event: clears every Cache Storage entry when the
3
+ * browser has Cache Storage, then reloads the page with a cache-busting query.
4
+ * A failed cache clear is reported and the page still reloads.
5
+ */
6
+ export function clearCachesAndReload(win) {
7
+ const reloadWithCacheBust = () => {
8
+ const nextUrl = new URL(win.location.href);
9
+ nextUrl.searchParams.set('_reload', Date.now().toString());
10
+ win.location.replace(nextUrl.toString());
11
+ };
12
+ const caches = win.caches;
13
+ if (!caches) {
14
+ reloadWithCacheBust();
15
+ return;
16
+ }
17
+ void caches.keys()
18
+ .then((keys) => Promise.all(keys.map((key) => caches.delete(key))))
19
+ .catch((err) => { console.warn('[program_reload] cache clear failed:', err); })
20
+ .finally(() => { reloadWithCacheBust(); });
21
+ }
@@ -1,6 +1,11 @@
1
1
  import { type NewsItem } from '../components/slides/ArticleSlide.js';
2
2
  import type { Segment } from './types.js';
3
3
  import { type SupportedLanguage } from '../i18n.js';
4
+ /**
5
+ * The homepage feed's stories. When the feed fails, the last good stories for
6
+ * the language stay for up to 30 minutes (fifthbell/brokaw#35); after that, or
7
+ * when there never were any, the built-in sample stories fill the segment.
8
+ */
4
9
  export declare function fetchArticles(language?: SupportedLanguage): Promise<NewsItem[]>;
5
10
  export declare function createArticlesSegment(articles: NewsItem[], onDataUpdate?: (nextArticles: NewsItem[]) => void, language?: SupportedLanguage): Segment;
6
11
  export type { NewsItem };
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useRef, useState } from 'react';
3
+ import { createLastGood } from '../source-retention.js';
3
4
  import { ArticleSlide } from '../components/slides/ArticleSlide.js';
4
5
  import { t } from '../i18n.js';
5
6
  const MOCK_ARTICLES = [
@@ -45,8 +46,6 @@ const MOCK_ARTICLES = [
45
46
  }
46
47
  ];
47
48
  function normalizePath(input) {
48
- if (!input)
49
- return '/';
50
49
  const stripped = input.split('?')[0] || '/';
51
50
  const normalized = `/${stripped.replace(/^\/+/, '')}`.replace(/\/{2,}/g, '/');
52
51
  return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
@@ -72,6 +71,12 @@ function buildArticlePath(article, language) {
72
71
  : `/${language}/${primaryCategorySlug}/${bareSlug.replace(/^\//, '')}`
73
72
  : normalizePath(bareSlug || article.canonicalUrl || '/')));
74
73
  }
74
+ const lastGoodArticles = createLastGood();
75
+ /**
76
+ * The homepage feed's stories. When the feed fails, the last good stories for
77
+ * the language stay for up to 30 minutes (fifthbell/brokaw#35); after that, or
78
+ * when there never were any, the built-in sample stories fill the segment.
79
+ */
75
80
  export async function fetchArticles(language = 'en') {
76
81
  try {
77
82
  const response = await fetch(`https://cdn.fifthbell.com/content/homepage-current-${language}.json?_=${Date.now()}`, {
@@ -107,19 +112,20 @@ export async function fetchArticles(language = 'en') {
107
112
  image.crossOrigin = 'anonymous';
108
113
  image.src = item.imageUrl;
109
114
  });
110
- return finalItems;
115
+ return lastGoodArticles.keep(language, finalItems);
111
116
  }
112
117
  catch (error) {
113
118
  console.error('Error fetching news items:', error);
114
- return MOCK_ARTICLES;
119
+ return lastGoodArticles.recall(language) ?? MOCK_ARTICLES;
115
120
  }
116
121
  }
117
- function ArticlesSegmentRenderer({ items, itemIndex, progress, language }) {
122
+ function ArticlesSegmentRenderer({ items, itemIndex, progress }) {
118
123
  const [displayedIndex, setDisplayedIndex] = useState(itemIndex);
119
124
  const [isTransitioning, setIsTransitioning] = useState(false);
120
125
  const previousIndexRef = useRef(itemIndex);
121
126
  useEffect(() => {
122
- if (itemIndex !== previousIndexRef.current && items.length > 0) {
127
+ // items is never empty: the segment falls back to its sample stories.
128
+ if (itemIndex !== previousIndexRef.current) {
123
129
  setIsTransitioning(true);
124
130
  const timer = window.setTimeout(() => {
125
131
  setDisplayedIndex(itemIndex);
@@ -130,12 +136,9 @@ function ArticlesSegmentRenderer({ items, itemIndex, progress, language }) {
130
136
  }
131
137
  return undefined;
132
138
  }, [itemIndex, items.length]);
133
- if (items.length === 0) {
134
- return _jsx("div", { className: 'text-white', children: t('articles.noArticles', language) });
135
- }
136
139
  const currentItem = items[itemIndex % items.length];
137
140
  const previousItem = items[displayedIndex % items.length];
138
- return (_jsxs("div", { className: 'relative w-full h-full', children: [isTransitioning && previousItem && (_jsx("div", { className: 'absolute inset-0', children: _jsx(ArticleSlide, { newsItem: previousItem, progress: 100 }) })), _jsx("div", { className: `absolute inset-0 ${isTransitioning ? 'animate-slide-transition' : ''}`, children: _jsx(ArticleSlide, { newsItem: currentItem, progress: progress }) })] }));
141
+ return (_jsxs("div", { className: 'relative w-full h-full', children: [isTransitioning && (_jsx("div", { className: 'absolute inset-0', children: _jsx(ArticleSlide, { newsItem: previousItem, progress: 100 }) })), _jsx("div", { className: `absolute inset-0 ${isTransitioning ? 'animate-slide-transition' : ''}`, children: _jsx(ArticleSlide, { newsItem: currentItem, progress: progress }) })] }));
139
142
  }
140
143
  export function createArticlesSegment(articles, onDataUpdate, language = 'en') {
141
144
  return {
@@ -147,7 +150,8 @@ export function createArticlesSegment(articles, onDataUpdate, language = 'en') {
147
150
  durationMsPerItem: 10000,
148
151
  render: (itemIndex, progress) => {
149
152
  const items = articles.length > 0 ? articles : MOCK_ARTICLES;
150
- return _jsx(ArticlesSegmentRenderer, { items: items, itemIndex: itemIndex, progress: progress, language: language }, `article-${itemIndex}`);
153
+ // One key for the whole segment: the renderer persists across items and plays its transition.
154
+ return _jsx(ArticlesSegmentRenderer, { items: items, itemIndex: itemIndex, progress: progress }, 'articles');
151
155
  },
152
156
  prefetch: async () => {
153
157
  if (!onDataUpdate) {
@@ -12,5 +12,9 @@ export interface EarthquakeData {
12
12
  sources: string[];
13
13
  detailedPlace?: string;
14
14
  }
15
+ /**
16
+ * The last day's notable earthquakes. When the service fails, the last good
17
+ * list for the language stays for up to 30 minutes (fifthbell/brokaw#35), then drops.
18
+ */
15
19
  export declare function fetchEarthquakes(language?: SupportedLanguage): Promise<EarthquakeData[]>;
16
20
  export declare function createEarthquakeSegment(earthquakes: EarthquakeData[], onDataUpdate?: (data: EarthquakeData[]) => void, language?: SupportedLanguage): Segment;
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useState } from 'react';
3
+ import { createLastGood } from '../source-retention.js';
3
4
  import { AlertTriangle, Clock, Layers, Link, MapPin } from 'lucide-react';
4
5
  import { FastAverageColor } from 'fast-average-color';
5
6
  import { FIFTHBELL_ASSETS } from '../assets.js';
@@ -21,11 +22,16 @@ function formatTimeAgo(timestamp, language = 'en') {
21
22
  }
22
23
  return t('earthquakes.timeAgo.justNow', language);
23
24
  }
25
+ const lastGoodEarthquakes = createLastGood();
26
+ /**
27
+ * The last day's notable earthquakes. When the service fails, the last good
28
+ * list for the language stays for up to 30 minutes (fifthbell/brokaw#35), then drops.
29
+ */
24
30
  export async function fetchEarthquakes(language = 'en') {
25
31
  try {
26
32
  const response = await fetch(`https://api.monitor.gaulatti.com/earthquakes?_=${Date.now()}`);
27
33
  if (!response.ok) {
28
- return [];
34
+ throw new Error(`Failed to fetch earthquakes: ${response.status}`);
29
35
  }
30
36
  const data = await response.json();
31
37
  const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
@@ -33,7 +39,7 @@ export async function fetchEarthquakes(language = 'en') {
33
39
  .filter((quake) => quake.magnitude >= 4.5 && new Date(quake.timestamp).getTime() >= oneDayAgo)
34
40
  .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
35
41
  .slice(0, 6);
36
- return recentQuakes.map((quake) => {
42
+ return lastGoodEarthquakes.keep(language, recentQuakes.map((quake) => {
37
43
  const timestamp = new Date(quake.timestamp).getTime();
38
44
  let detailedPlace = '';
39
45
  const sources = [];
@@ -58,11 +64,11 @@ export async function fetchEarthquakes(language = 'en') {
58
64
  sources: [...new Set(sources)],
59
65
  detailedPlace
60
66
  };
61
- });
67
+ }));
62
68
  }
63
69
  catch (error) {
64
70
  console.error('Failed to fetch earthquake data:', error);
65
- return [];
71
+ return lastGoodEarthquakes.recall(language) ?? [];
66
72
  }
67
73
  }
68
74
  function getMagnitudeColor(magnitude) {
@@ -86,15 +92,12 @@ function EarthquakeSlide({ earthquakes, progress, language }) {
86
92
  setDominantColor('#7c2d12');
87
93
  }
88
94
  };
89
- if (earthquakes.length === 0) {
90
- return (_jsxs("div", { className: 'absolute inset-0', children: [_jsx("div", { className: 'absolute inset-0 opacity-75', style: { background: 'linear-gradient(to bottom right, #7c2d12, #000000)' } }), _jsx("div", { className: 'relative z-10 h-full flex items-center justify-center', children: _jsx("div", { className: 'text-4xl font-light font-secondary', children: t('earthquakes.noData', language) }) })] }));
91
- }
95
+ // The earthquakes segment shows its loading slide instead of this one when the list is empty.
92
96
  return (_jsxs("div", { className: 'absolute inset-0 animate-slide-transition', children: [_jsx("div", { className: 'absolute inset-0', children: _jsx("img", { src: backgroundImage, alt: '', crossOrigin: 'anonymous', onLoad: handleImageLoad, className: 'w-full h-full object-cover blur-xl scale-105' }, backgroundImage) }), _jsx("div", { className: 'absolute inset-0 opacity-75 mix-blend-multiply transition-all duration-1000', style: { background: `linear-gradient(to bottom right, ${dominantColor}, #000000)` } }), _jsx("div", { className: 'absolute inset-0 bg-[radial-gradient(circle_at_30%_30%,rgba(255,255,255,0.1),transparent_60%)]' }), _jsxs("div", { className: 'relative z-10 h-full flex flex-col justify-center px-24 py-24', children: [_jsxs("div", { className: 'mb-8 animate-slide-up', children: [_jsx("div", { className: 'w-32 h-2 bg-white mb-8' }), _jsxs("div", { className: 'flex items-center space-x-4 mb-4', children: [_jsx(AlertTriangle, { size: 56, className: 'text-orange-500', strokeWidth: 2 }), _jsx("h1", { className: 'text-5xl font-bold tracking-tight leading-tight font-encode', children: t('earthquakes.header', language) })] }), _jsx("p", { className: 'text-2xl font-light font-secondary opacity-90 leading-relaxed', children: t('earthquakes.subtitle', language) })] }), _jsx("div", { className: 'grid grid-cols-2 gap-6 animate-slide-up', children: earthquakes.map((quake, index) => {
93
97
  const baseColor = getMagnitudeColor(quake.magnitude);
98
+ // getMagnitudeColor only returns #rrggbb literals, so the pattern always matches.
94
99
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(baseColor);
95
- const rgb = result
96
- ? { r: Number.parseInt(result[1], 16), g: Number.parseInt(result[2], 16), b: Number.parseInt(result[3], 16) }
97
- : { r: 239, g: 68, b: 68 };
100
+ const rgb = { r: Number.parseInt(result[1], 16), g: Number.parseInt(result[2], 16), b: Number.parseInt(result[3], 16) };
98
101
  let magnitudeIntensity;
99
102
  if (quake.magnitude < 5.0) {
100
103
  magnitudeIntensity = (quake.magnitude - 4.5) / 0.5;