-
Notifications
You must be signed in to change notification settings - Fork 10.2k
Expand file tree
/
Copy pathvite.config.ts
More file actions
1663 lines (1585 loc) · 73.6 KB
/
Copy pathvite.config.ts
File metadata and controls
1663 lines (1585 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { defineConfig, loadEnv, type Plugin } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
import type { OutputBundle } from 'rollup';
import { resolve, dirname, extname } from 'path';
import { mkdir, readFile, writeFile } from 'fs/promises';
import { brotliCompress } from 'zlib';
import { promisify } from 'util';
import pkg from './package.json';
import { VARIANT_META, type VariantMeta } from './src/config/variant-meta';
import {
WEB_DASHBOARD_VARIANTS,
renderVariantDashboardHtml,
variantDashboardFileName,
} from './src/config/variant-dashboard-html';
// Single source of truth for the RSS proxy allowlist — the dev-server proxy
// below reuses the SAME www-tolerant predicate the Edge handler enforces
// (api/rss-proxy.js) so dev and prod agree on allow/deny. Previously a
// hand-maintained Set here had drifted ~138 domains from prod.
import { isAllowedDomain } from './api/_rss-allowed-domain-match.js';
// Env-dependent constants moved inside defineConfig function
const brotliCompressAsync = promisify(brotliCompress);
const BROTLI_EXTENSIONS = new Set(['.js', '.mjs', '.css', '.html', '.svg', '.json', '.txt', '.xml', '.wasm']);
const STATIC_SCRIPT_NONCE = 'wm-static-bootstrap';
// @clerk/clerk-js is loaded as a UMD bundle from the Clerk Frontend API at
// runtime (src/services/clerk.ts), not bundled. Resolve the version from
// package.json so the runtime SDK matches the @clerk/clerk-js types we compile
// against, and inject it via `define` (__CLERK_JS_VERSION__). Fall back to
// devDependencies in case the (types-only) dep is moved there, and fail the
// build loudly if it can't be resolved — an empty version yields a `.../@/dist`
// URL that 404s and silently breaks auth in production.
const CLERK_DEPS = pkg.dependencies as Record<string, string>;
const CLERK_DEV_DEPS = (pkg.devDependencies ?? {}) as Record<string, string>;
const CLERK_JS_VERSION = (CLERK_DEPS['@clerk/clerk-js'] || CLERK_DEV_DEPS['@clerk/clerk-js'] || '')
.replace(/^[\^~>=<\s]*/, '');
if (!CLERK_JS_VERSION) {
throw new Error('[vite] @clerk/clerk-js not found in package.json — __CLERK_JS_VERSION__ would be empty and 404 the Clerk Frontend API script URL.');
}
// @clerk/ui (the runtime UI controller, pinned by CLERK_UI_VERSION in
// src/services/clerk.ts) is major 1, which pairs with @clerk/clerk-js major 6.
// Fail the build if the SDK major drifts so the pairing is updated deliberately
// rather than loading an incompatible UI controller and breaking auth at runtime.
if (CLERK_JS_VERSION.split('.')[0] !== '6') {
throw new Error(`[vite] @clerk/clerk-js major is ${CLERK_JS_VERSION.split('.')[0]}, expected 6 — update CLERK_UI_VERSION in src/services/clerk.ts to the paired @clerk/ui major, then bump this guard.`);
}
const PANEL_CHUNK_NAMES = [
'panels-markets',
'panels-energy',
'panels-defense',
'panels-news',
'panels-economy',
'panels-intel',
'panels-risk',
] as const;
type PanelChunkName = typeof PANEL_CHUNK_NAMES[number];
const PANEL_SUPPORT_CHUNK_NAMES = ['panel-support'] as const;
type PanelSupportChunkName = typeof PANEL_SUPPORT_CHUNK_NAMES[number];
type PanelManualChunkName = PanelChunkName | PanelSupportChunkName;
// Single source of truth for chunk names that must NOT be hoisted into the
// entry HTML's modulepreload list. Used by both `manualChunks` (return values
// must literally match these strings) and `modulePreload.resolveDependencies`
// (filter regex is built from this list). Keeping them tied prevents the
// silent-breakage failure mode where renaming a chunk in `manualChunks`
// re-eagerises the WebGL stack without any build-time error.
// - maplibre, deck-stack, protomaps: heavy WebGL deps, only reachable via MapContainer
// - MapContainer: the dynamic-import target itself
// - panels-*: panel domain chunks; keep them out of the entry HTML preload
// - UnifiedSettings, settings-window, checkout: secondary interaction flows;
// first paint only needs their header buttons and cheap event wiring
const LAZY_HTML_PRELOAD_CHUNKS = [
'maplibre',
'deck-stack',
'protomaps',
'h3-js',
'MapContainer',
'UnifiedSettings',
'settings-window',
'checkout',
...PANEL_CHUNK_NAMES,
...PANEL_SUPPORT_CHUNK_NAMES,
] as const;
const LAZY_HTML_PRELOAD_RE = new RegExp(
`/(?:${LAZY_HTML_PRELOAD_CHUNKS.join('|')}|rpc-client-[A-Za-z0-9_-]+)-[A-Za-z0-9_-]+\\.js$`,
);
// Panel-cluster manualChunks map. Splits the previously monolithic ~2.3MB
// `panels` chunk into per-domain chunks so cache invalidation is local to
// the cluster a panel lives in and per-variant builds can prune unused
// clusters. New panel files must be assigned here before the build can split
// them; otherwise they would silently fall back into an eager catch-all chunk.
const PANEL_CLUSTER: Record<string, PanelChunkName> = {
// Markets / equities / crypto positioning
AAIISentiment: 'panels-markets', CotPositioning: 'panels-markets',
ETFFlows: 'panels-markets', EarningsCalendar: 'panels-markets',
EconomicCalendar: 'panels-markets', FearGreed: 'panels-markets',
GoldIntelligence: 'panels-markets', LiquidityShifts: 'panels-markets',
MacroSignals: 'panels-markets', Market: 'panels-markets',
MarketBreadth: 'panels-markets', MarketImplications: 'panels-markets',
Positioning: 'panels-markets', Stablecoin: 'panels-markets',
StockAnalysis: 'panels-markets', StockBacktest: 'panels-markets',
WsbTickerScanner: 'panels-markets', YieldCurve: 'panels-markets',
// Energy / commodities / supply infra
ChokepointStrip: 'panels-energy', EnergyComplex: 'panels-energy',
EnergyCrisis: 'panels-energy', EnergyDisruptions: 'panels-energy',
EnergyRiskOverview: 'panels-energy', FuelPrices: 'panels-energy',
FuelShortage: 'panels-energy', Hormuz: 'panels-energy',
OilInventories: 'panels-energy', PipelineStatus: 'panels-energy',
StorageFacilityMap: 'panels-energy', RenewableEnergy: 'panels-energy',
// Defense / military / aviation
AirlineIntel: 'panels-defense', DefensePatents: 'panels-defense',
OrefSirens: 'panels-defense', StrategicPosture: 'panels-defense',
StrategicRisk: 'panels-defense', ThermalEscalation: 'panels-defense',
UcdpEvents: 'panels-defense',
// News / feeds / briefs
BreakthroughsTicker: 'panels-news', ClimateNews: 'panels-news',
DailyMarketBrief: 'panels-news', GdeltIntel: 'panels-news',
GoodThingsDigest: 'panels-news', LatestBrief: 'panels-news',
LiveNews: 'panels-news', News: 'panels-news',
PositiveNewsFeed: 'panels-news', TelegramIntel: 'panels-news',
// Macro / prices / trade
BigMac: 'panels-economy', ConsumerPrices: 'panels-economy',
Economic: 'panels-economy', GlobalProcurement: 'panels-economy',
FaoFoodPriceIndex: 'panels-economy', FSI: 'panels-economy',
GroceryBasket: 'panels-economy', GulfEconomies: 'panels-economy',
Investments: 'panels-economy', MacroTiles: 'panels-economy',
NationalDebt: 'panels-economy', SanctionsPressure: 'panels-economy',
SupplyChain: 'panels-economy', TradePolicy: 'panels-economy',
// Country briefs / signals / monitors / agent surfaces.
// CorrelationPanel base lives here, so all *Correlation consumers MUST stay
// in this cluster — splitting them across clusters caused TDZ on init.
ChatAnalyst: 'panels-intel', CII: 'panels-intel',
Cascade: 'panels-intel', Correlation: 'panels-intel',
CountryBrief: 'panels-intel', CountryBriefPage: 'panels-intel',
CountryDeepDive: 'panels-intel',
CrossSourceSignals: 'panels-intel', CustomWidget: 'panels-intel',
Deduction: 'panels-intel',
DisasterCorrelation: 'panels-intel',
EconomicCorrelation: 'panels-intel',
EscalationCorrelation: 'panels-intel',
MilitaryCorrelation: 'panels-intel',
Forecast: 'panels-intel',
HeroSpotlight: 'panels-intel', Insights: 'panels-intel',
LiveWebcams: 'panels-intel', McpData: 'panels-intel',
Monitor: 'panels-intel', PinnedWebcams: 'panels-intel',
Prediction: 'panels-intel', ProgressCharts: 'panels-intel',
RegionalIntelligenceBoard: 'panels-intel',
Regulation: 'panels-intel',
// Disasters / climate / connectivity / society
ClimateAnomaly: 'panels-risk', Counters: 'panels-risk',
DiseaseOutbreaks: 'panels-risk',
Displacement: 'panels-risk', GeoHubs: 'panels-risk',
Giving: 'panels-risk', InternetDisruptions: 'panels-risk',
PopulationExposure: 'panels-risk', RadiationWatch: 'panels-risk',
RuntimeConfig: 'panels-risk', SatelliteFires: 'panels-risk',
SecurityAdvisories: 'panels-risk', ServiceStatus: 'panels-risk',
SocialVelocity: 'panels-risk', SpeciesComeback: 'panels-risk',
TechEvents: 'panels-risk',
ThreatTimeline: 'panels-risk',
TechHubs: 'panels-risk', TechReadiness: 'panels-risk',
WorldClock: 'panels-risk',
};
const PANEL_SUPPORT_CLUSTER: Record<string, PanelSupportChunkName> = {
Status: 'panel-support',
};
function panelKeyForComponentId(id: string): string | null {
if (!id.includes('/src/components/') || !id.endsWith('.ts')) return null;
const match = id.match(/\/([^/]+)\.ts$/);
if (!match) return null;
const fileBase = match[1];
if (fileBase === 'Panel') return null;
if (fileBase === 'CountryBriefPage' || fileBase === 'RegionalIntelligenceBoard') return fileBase;
if (fileBase.endsWith('Panel')) return fileBase.slice(0, -'Panel'.length);
return null;
}
function panelChunkForComponentId(id: string): PanelManualChunkName | null {
const panelKey = panelKeyForComponentId(id);
if (!panelKey) return null;
const chunkName = PANEL_SUPPORT_CLUSTER[panelKey] ?? PANEL_CLUSTER[panelKey];
if (chunkName) return chunkName;
throw new Error(`[manualChunks] Unassigned panel component ${panelKey}. Add it to PANEL_CLUSTER or PANEL_SUPPORT_CLUSTER in vite.config.ts.`);
}
function brotliPrecompressPlugin(): Plugin {
return {
name: 'brotli-precompress',
apply: 'build',
async writeBundle(outputOptions, bundle) {
const outDir = outputOptions.dir;
if (!outDir) return;
await Promise.all(Object.keys(bundle).map(async (fileName) => {
const extension = extname(fileName).toLowerCase();
if (!BROTLI_EXTENSIONS.has(extension)) return;
const sourcePath = resolve(outDir, fileName);
const compressedPath = `${sourcePath}.br`;
const sourceBuffer = await readFile(sourcePath);
if (sourceBuffer.length < 1024) return;
const compressedBuffer = await brotliCompressAsync(sourceBuffer);
await mkdir(dirname(compressedPath), { recursive: true });
await writeFile(compressedPath, compressedBuffer);
}));
},
};
}
function htmlVariantPlugin(activeMeta: VariantMeta, activeVariant: string, isDesktopBuild: boolean): Plugin {
return {
name: 'html-variant',
transformIndexHtml(html) {
let result = html
.replace(/<title>.*?<\/title>/, `<title>${activeMeta.title}</title>`)
.replace(/<meta name="title" content=".*?" \/>/, `<meta name="title" content="${activeMeta.title}" />`)
.replace(/<meta name="description" content=".*?" \/>/, `<meta name="description" content="${activeMeta.description}" />`)
.replace(/<meta name="keywords" content=".*?" \/>/, `<meta name="keywords" content="${activeMeta.keywords}" />`)
.replace(/<link rel="canonical" href=".*?" \/>/, `<link rel="canonical" href="${activeMeta.url}" />`)
.replace(/<meta name="application-name" content=".*?" \/>/, `<meta name="application-name" content="${activeMeta.siteName}" />`)
.replace(/<meta property="og:url" content=".*?" \/>/, `<meta property="og:url" content="${activeMeta.url}" />`)
.replace(/<meta property="og:title" content=".*?" \/>/, `<meta property="og:title" content="${activeMeta.title}" />`)
.replace(/<meta property="og:description" content=".*?" \/>/, `<meta property="og:description" content="${activeMeta.description}" />`)
.replace(/<meta property="og:site_name" content=".*?" \/>/, `<meta property="og:site_name" content="${activeMeta.siteName}" />`)
.replace(/<meta name="subject" content=".*?" \/>/, `<meta name="subject" content="${activeMeta.subject}" />`)
.replace(/<meta name="classification" content=".*?" \/>/, `<meta name="classification" content="${activeMeta.classification}" />`)
.replace(/<meta name="twitter:url" content=".*?" \/>/, `<meta name="twitter:url" content="${activeMeta.url}" />`)
.replace(/<meta name="twitter:title" content=".*?" \/>/, `<meta name="twitter:title" content="${activeMeta.title}" />`)
.replace(/<meta name="twitter:description" content=".*?" \/>/, `<meta name="twitter:description" content="${activeMeta.description}" />`)
.replace(/"name": "World Monitor"/, `"name": "${activeMeta.siteName}"`)
.replace(/"alternateName": "WorldMonitor"/, `"alternateName": "${activeMeta.siteName.replace(' ', '')}"`)
.replace(/"url": "https:\/\/worldmonitor\.app\/"/, `"url": "${activeMeta.url}"`)
.replace(/"description": "Real-time global intelligence dashboard with live news, markets, military tracking, infrastructure monitoring, and geopolitical data."/, `"description": "${activeMeta.description}"`)
.replace(/"featureList": \[[\s\S]*?\]/, `"featureList": ${JSON.stringify(activeMeta.features, null, 8).replace(/\n/g, '\n ')}`);
// Theme-color meta — warm cream for happy variant
if (activeVariant === 'happy') {
result = result.replace(
/<meta name="theme-color" content=".*?" \/>/,
'<meta name="theme-color" content="#FAFAF5" />'
);
}
// Desktop builds: inject build-time variant into the inline script so data-variant is set
// before CSS loads. Web builds always use 'full' — runtime hostname detection handles variants.
if (activeVariant !== 'full') {
result = result.replace(
/if\(v\)document\.documentElement\.dataset\.variant=v;/,
`v='${activeVariant}';document.documentElement.dataset.variant=v;`
);
}
// Desktop CSP: inject localhost wildcard for dynamic sidecar port.
// Web builds intentionally exclude localhost to avoid exposing attack surface.
if (isDesktopBuild) {
result = result
.replace(
/connect-src 'self' https: http:\/\/localhost:5173/,
"connect-src 'self' https: http://localhost:5173 http://127.0.0.1:*"
)
.replace(
/frame-src 'self'/,
"frame-src 'self' http://127.0.0.1:*"
);
}
// Desktop builds: replace favicon paths with variant-specific subdirectory.
// Web builds use 'full' favicons in HTML; runtime JS swaps them per hostname.
if (activeVariant !== 'full') {
result = result
.replace(/\/favico\/favicon/g, `/favico/${activeVariant}/favicon`)
.replace(/\/favico\/apple-touch-icon/g, `/favico/${activeVariant}/apple-touch-icon`)
.replace(/\/favico\/android-chrome/g, `/favico/${activeVariant}/android-chrome`)
.replace(/\/favico\/og-image/g, `/favico/${activeVariant}/og-image`);
}
return result;
},
};
}
function dashboardHtmlOutputPlugin(): Plugin {
return {
name: 'wm-dashboard-html-output',
apply: 'build',
enforce: 'post',
generateBundle(_options, bundle) {
const dashboardEntry = Object.entries(bundle).find(([, output]) =>
output.type === 'asset' && output.fileName === 'index.html'
);
if (!dashboardEntry) {
throw new Error('[vite] expected dashboard HTML entry index.html before renaming it to dashboard.html');
}
const [bundleKey, dashboardHtml] = dashboardEntry;
delete bundle[bundleKey];
dashboardHtml.fileName = 'dashboard.html';
if (typeof dashboardHtml.source === 'string') {
dashboardHtml.source = deferDashboardStylesheetLinks(dashboardHtml.source, bundle);
}
bundle['dashboard.html'] = dashboardHtml;
},
};
}
// Emit dashboard-<variant>.html siblings of dashboard.html for the variant
// subdomains (#4996). The web deployment serves the 'full' build to every
// host, so tech/finance/commodity/happy/energy.worldmonitor.app/dashboard
// shipped full-brand meta and a cross-host canonical pointing at www —
// crawlers saw five duplicate pages that all declared themselves NOT to be
// the sitemap URL they were fetched from. vercel.json host-based rewrites
// map each variant host's /dashboard to its generated file. Runs in
// generateBundle AFTER dashboardHtmlOutputPlugin (both enforce: 'post',
// registered later in the plugins array) so it reads the final renamed +
// stylesheet-deferred dashboard.html; emitted via emitFile so
// brotliPrecompressPlugin picks the files up like any other asset.
function variantDashboardHtmlPlugin(): Plugin {
return {
name: 'wm-variant-dashboard-html',
apply: 'build',
enforce: 'post',
generateBundle(_options, bundle) {
const dashboard = bundle['dashboard.html'];
if (!dashboard || dashboard.type !== 'asset' || typeof dashboard.source !== 'string') {
throw new Error('[vite] wm-variant-dashboard-html expected dashboard.html asset (must run after wm-dashboard-html-output)');
}
for (const variant of WEB_DASHBOARD_VARIANTS) {
this.emitFile({
type: 'asset',
fileName: variantDashboardFileName(variant),
source: renderVariantDashboardHtml(dashboard.source, variant),
});
}
},
};
}
function shouldDeferDashboardStylesheet(tag: string, bundle: OutputBundle): boolean {
const href = tag.match(/\bhref=["']([^"']+\.css)["']/i)?.[1];
if (!href) return false;
const bundleKey = href.replace(/^\//, '');
const asset = bundle[bundleKey];
if (!asset || asset.type !== 'asset') return false;
const sourceLength = typeof asset.source === 'string'
? Buffer.byteLength(asset.source)
: asset.source.byteLength;
return sourceLength >= 100 * 1024;
}
// Rewrite large render-blocking dashboard <link rel=stylesheet> tags into a
// deferred form (media="print" + data-wm-deferred-style="dashboard") plus a
// <noscript> copy of the original blocking link, so the ~492KB app CSS no
// longer blocks first paint. src/main.ts activateDeferredDashboardStyles()
// flips media -> "all" at startup; the attribute name + values written here MUST
// stay in lockstep with that runtime selector. Only assets >=100KB are deferred
// (shouldDeferDashboardStylesheet) so small stylesheets stay blocking; links
// that already set media= (an intentionally print/screen-scoped sheet) or are
// already deferred are skipped. NOTE: during the defer window only the UNLAYERED
// inline critical CSS in index.html applies (the bundle is @layer base), so any
// future *unconditional* inline rule will beat the bundle (see PR #4346) — keep
// inline rules scoped to a transient/closed state.
function deferDashboardStylesheetLinks(html: string, bundle: OutputBundle): string {
return html.replace(/<link\b(?=[^>]*\brel=["']stylesheet["'])(?=[^>]*\bhref=["'][^"']+\.css["'])[^>]*>/gi, (tag) => {
if (/\bdata-wm-deferred-style=/.test(tag) || /\bmedia=/.test(tag)) return tag;
if (!shouldDeferDashboardStylesheet(tag, bundle)) return tag;
const deferredTag = tag.replace(/\s*\/?>$/, ' media="print" data-wm-deferred-style="dashboard">');
return `${deferredTag}\n <noscript>${tag}</noscript>`;
});
}
function polymarketPlugin(): Plugin {
const GAMMA_BASE = 'https://gamma-api.polymarket.com';
const ALLOWED_ORDER = ['volume', 'liquidity', 'startDate', 'endDate', 'spread'];
return {
name: 'polymarket-dev',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (!req.url?.startsWith('/api/polymarket')) return next();
const url = new URL(req.url, 'http://localhost');
const endpoint = url.searchParams.get('endpoint') || 'markets';
const closed = ['true', 'false'].includes(url.searchParams.get('closed') ?? '') ? url.searchParams.get('closed') : 'false';
const order = ALLOWED_ORDER.includes(url.searchParams.get('order') ?? '') ? url.searchParams.get('order') : 'volume';
const ascending = ['true', 'false'].includes(url.searchParams.get('ascending') ?? '') ? url.searchParams.get('ascending') : 'false';
const rawLimit = parseInt(url.searchParams.get('limit') ?? '', 10);
const limit = isNaN(rawLimit) ? 50 : Math.max(1, Math.min(100, rawLimit));
const params = new URLSearchParams({ closed: closed!, order: order!, ascending: ascending!, limit: String(limit) });
if (endpoint === 'events') {
const tag = (url.searchParams.get('tag') ?? '').replace(/[^a-z0-9-]/gi, '').slice(0, 100);
if (tag) params.set('tag_slug', tag);
}
const gammaUrl = `${GAMMA_BASE}/${endpoint === 'events' ? 'events' : 'markets'}?${params}`;
res.setHeader('Content-Type', 'application/json');
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);
const resp = await fetch(gammaUrl, { headers: { Accept: 'application/json' }, signal: controller.signal });
clearTimeout(timer);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.text();
res.setHeader('Cache-Control', 'public, max-age=120');
res.setHeader('X-Polymarket-Source', 'gamma');
res.end(data);
} catch {
// Expected: Cloudflare JA3 blocks server-side TLS — return empty array
res.setHeader('Cache-Control', 'public, max-age=300');
res.end('[]');
}
});
},
};
}
/**
* Vite dev server plugin for sebuf API routes.
*
* Intercepts requests matching /api/{domain}/v1/* and routes them through
* the same handler pipeline as the Vercel catch-all gateway. Other /api/*
* paths fall through to existing proxy rules.
*/
function sebufApiPlugin(): Plugin {
// Cache router across requests (H-13 fix). Invalidated by Vite's module graph on HMR.
let cachedRouter: Awaited<ReturnType<typeof buildRouter>> | null = null;
let cachedCorsMod: any = null;
async function buildRouter() {
const [
routerMod, corsMod, errorMod,
seismologyServerMod, seismologyHandlerMod,
wildfireServerMod, wildfireHandlerMod,
climateServerMod, climateHandlerMod,
predictionServerMod, predictionHandlerMod,
displacementServerMod, displacementHandlerMod,
aviationServerMod, aviationHandlerMod,
researchServerMod, researchHandlerMod,
unrestServerMod, unrestHandlerMod,
conflictServerMod, conflictHandlerMod,
maritimeServerMod, maritimeHandlerMod,
cyberServerMod, cyberHandlerMod,
economicServerMod, economicHandlerMod,
infrastructureServerMod, infrastructureHandlerMod,
marketServerMod, marketHandlerMod,
newsServerMod, newsHandlerMod,
intelligenceServerMod, intelligenceHandlerMod,
militaryServerMod, militaryHandlerMod,
positiveEventsServerMod, positiveEventsHandlerMod,
givingServerMod, givingHandlerMod,
tradeServerMod, tradeHandlerMod,
supplyChainServerMod, supplyChainHandlerMod,
naturalServerMod, naturalHandlerMod,
resilienceServerMod, resilienceHandlerMod,
leadsServerMod, leadsHandlerMod,
scenarioServerMod, scenarioHandlerMod,
shippingV2ServerMod, shippingV2HandlerMod,
] = await Promise.all([
import('./server/router'),
import('./server/cors'),
import('./server/error-mapper'),
import('./src/generated/server/worldmonitor/seismology/v1/service_server'),
import('./server/worldmonitor/seismology/v1/handler'),
import('./src/generated/server/worldmonitor/wildfire/v1/service_server'),
import('./server/worldmonitor/wildfire/v1/handler'),
import('./src/generated/server/worldmonitor/climate/v1/service_server'),
import('./server/worldmonitor/climate/v1/handler'),
import('./src/generated/server/worldmonitor/prediction/v1/service_server'),
import('./server/worldmonitor/prediction/v1/handler'),
import('./src/generated/server/worldmonitor/displacement/v1/service_server'),
import('./server/worldmonitor/displacement/v1/handler'),
import('./src/generated/server/worldmonitor/aviation/v1/service_server'),
import('./server/worldmonitor/aviation/v1/handler'),
import('./src/generated/server/worldmonitor/research/v1/service_server'),
import('./server/worldmonitor/research/v1/handler'),
import('./src/generated/server/worldmonitor/unrest/v1/service_server'),
import('./server/worldmonitor/unrest/v1/handler'),
import('./src/generated/server/worldmonitor/conflict/v1/service_server'),
import('./server/worldmonitor/conflict/v1/handler'),
import('./src/generated/server/worldmonitor/maritime/v1/service_server'),
import('./server/worldmonitor/maritime/v1/handler'),
import('./src/generated/server/worldmonitor/cyber/v1/service_server'),
import('./server/worldmonitor/cyber/v1/handler'),
import('./src/generated/server/worldmonitor/economic/v1/service_server'),
import('./server/worldmonitor/economic/v1/handler'),
import('./src/generated/server/worldmonitor/infrastructure/v1/service_server'),
import('./server/worldmonitor/infrastructure/v1/handler'),
import('./src/generated/server/worldmonitor/market/v1/service_server'),
import('./server/worldmonitor/market/v1/handler'),
import('./src/generated/server/worldmonitor/news/v1/service_server'),
import('./server/worldmonitor/news/v1/handler'),
import('./src/generated/server/worldmonitor/intelligence/v1/service_server'),
import('./server/worldmonitor/intelligence/v1/handler'),
import('./src/generated/server/worldmonitor/military/v1/service_server'),
import('./server/worldmonitor/military/v1/handler'),
import('./src/generated/server/worldmonitor/positive_events/v1/service_server'),
import('./server/worldmonitor/positive-events/v1/handler'),
import('./src/generated/server/worldmonitor/giving/v1/service_server'),
import('./server/worldmonitor/giving/v1/handler'),
import('./src/generated/server/worldmonitor/trade/v1/service_server'),
import('./server/worldmonitor/trade/v1/handler'),
import('./src/generated/server/worldmonitor/supply_chain/v1/service_server'),
import('./server/worldmonitor/supply-chain/v1/handler'),
import('./src/generated/server/worldmonitor/natural/v1/service_server'),
import('./server/worldmonitor/natural/v1/handler'),
import('./src/generated/server/worldmonitor/resilience/v1/service_server'),
import('./server/worldmonitor/resilience/v1/handler'),
import('./src/generated/server/worldmonitor/leads/v1/service_server'),
import('./server/worldmonitor/leads/v1/handler'),
import('./src/generated/server/worldmonitor/scenario/v1/service_server'),
import('./server/worldmonitor/scenario/v1/handler'),
import('./src/generated/server/worldmonitor/shipping/v2/service_server'),
import('./server/worldmonitor/shipping/v2/handler'),
]);
const serverOptions = { onError: errorMod.mapErrorToResponse };
const allRoutes = [
...seismologyServerMod.createSeismologyServiceRoutes(seismologyHandlerMod.seismologyHandler, serverOptions),
...wildfireServerMod.createWildfireServiceRoutes(wildfireHandlerMod.wildfireHandler, serverOptions),
...climateServerMod.createClimateServiceRoutes(climateHandlerMod.climateHandler, serverOptions),
...predictionServerMod.createPredictionServiceRoutes(predictionHandlerMod.predictionHandler, serverOptions),
...displacementServerMod.createDisplacementServiceRoutes(displacementHandlerMod.displacementHandler, serverOptions),
...aviationServerMod.createAviationServiceRoutes(aviationHandlerMod.aviationHandler, serverOptions),
...researchServerMod.createResearchServiceRoutes(researchHandlerMod.researchHandler, serverOptions),
...unrestServerMod.createUnrestServiceRoutes(unrestHandlerMod.unrestHandler, serverOptions),
...conflictServerMod.createConflictServiceRoutes(conflictHandlerMod.conflictHandler, serverOptions),
...maritimeServerMod.createMaritimeServiceRoutes(maritimeHandlerMod.maritimeHandler, serverOptions),
...cyberServerMod.createCyberServiceRoutes(cyberHandlerMod.cyberHandler, serverOptions),
...economicServerMod.createEconomicServiceRoutes(economicHandlerMod.economicHandler, serverOptions),
...infrastructureServerMod.createInfrastructureServiceRoutes(infrastructureHandlerMod.infrastructureHandler, serverOptions),
...marketServerMod.createMarketServiceRoutes(marketHandlerMod.marketHandler, serverOptions),
...newsServerMod.createNewsServiceRoutes(newsHandlerMod.newsHandler, serverOptions),
...intelligenceServerMod.createIntelligenceServiceRoutes(intelligenceHandlerMod.intelligenceHandler, serverOptions),
...militaryServerMod.createMilitaryServiceRoutes(militaryHandlerMod.militaryHandler, serverOptions),
...positiveEventsServerMod.createPositiveEventsServiceRoutes(positiveEventsHandlerMod.positiveEventsHandler, serverOptions),
...givingServerMod.createGivingServiceRoutes(givingHandlerMod.givingHandler, serverOptions),
...tradeServerMod.createTradeServiceRoutes(tradeHandlerMod.tradeHandler, serverOptions),
...supplyChainServerMod.createSupplyChainServiceRoutes(supplyChainHandlerMod.supplyChainHandler, serverOptions),
...naturalServerMod.createNaturalServiceRoutes(naturalHandlerMod.naturalHandler, serverOptions),
...resilienceServerMod.createResilienceServiceRoutes(resilienceHandlerMod.resilienceHandler, serverOptions),
...leadsServerMod.createLeadsServiceRoutes(leadsHandlerMod.leadsHandler, serverOptions),
...scenarioServerMod.createScenarioServiceRoutes(scenarioHandlerMod.scenarioHandler, serverOptions),
...shippingV2ServerMod.createShippingV2ServiceRoutes(shippingV2HandlerMod.shippingV2Handler, serverOptions),
];
cachedCorsMod = corsMod;
return routerMod.createRouter(allRoutes);
}
return {
name: 'sebuf-api',
configureServer(server) {
// Invalidate cached router on HMR updates to server/ files
server.watcher.on('change', (file) => {
if (file.includes('/server/') || file.includes('/src/generated/server/')) {
cachedRouter = null;
}
});
// Legacy v1 URL aliases → new sebuf RPC paths (mirror of the alias files
// in api/scenario/v1/ + api/supply-chain/v1/). Vercel serves the alias
// files directly; vite dev has no file-based routing for api/, so we
// rewrite the pathname here before the router lookup.
const V1_ALIASES: Record<string, string> = {
'/api/scenario/v1/run': '/api/scenario/v1/run-scenario',
'/api/scenario/v1/status': '/api/scenario/v1/get-scenario-status',
'/api/scenario/v1/templates': '/api/scenario/v1/list-scenario-templates',
'/api/supply-chain/v1/country-products': '/api/supply-chain/v1/get-country-products',
'/api/supply-chain/v1/multi-sector-cost-shock': '/api/supply-chain/v1/get-multi-sector-cost-shock',
};
server.middlewares.use(async (req, res, next) => {
// Intercept sebuf routes in two forms:
// - standard /api/{domain}/v{N}/* (domain-first, e.g. /api/market/v1/...)
// - partner-URL-preservation /api/v{N}/{domain}/* (version-first, e.g.
// /api/v2/shipping/...). Only the second form applies when the
// external contract already uses a reversed layout.
if (!req.url || !/^\/api\/(?:[a-z][a-z0-9-]*\/v\d+|v\d+\/[a-z][a-z0-9-]*)\//.test(req.url)) {
return next();
}
// Rewrite documented v1 URL → new sebuf path if this is an alias.
const [pathOnly, queryOnly] = req.url.split('?', 2);
const aliasTarget = pathOnly ? V1_ALIASES[pathOnly] : undefined;
if (aliasTarget) {
req.url = queryOnly ? `${aliasTarget}?${queryOnly}` : aliasTarget;
}
try {
// Build router once, reuse across requests (H-13 fix)
if (!cachedRouter) {
cachedRouter = await buildRouter();
}
const router = cachedRouter;
const corsMod = cachedCorsMod;
// Convert Connect IncomingMessage to Web Standard Request
const port = server.config.server.port || 3000;
const url = new URL(req.url, `http://localhost:${port}`);
// Read body for POST requests
let body: string | undefined;
if (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') {
const chunks: Buffer[] = [];
for await (const chunk of req) {
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
}
body = Buffer.concat(chunks).toString();
}
// Extract headers from IncomingMessage
const headers: Record<string, string> = {};
for (const [key, value] of Object.entries(req.headers)) {
if (typeof value === 'string') {
headers[key] = value;
} else if (Array.isArray(value)) {
headers[key] = value.join(', ');
}
}
const webRequest = new Request(url.toString(), {
method: req.method,
headers,
body: body || undefined,
});
const corsHeaders = corsMod.getCorsHeaders(webRequest);
// OPTIONS preflight
if (req.method === 'OPTIONS') {
res.statusCode = 204;
for (const [key, value] of Object.entries(corsHeaders)) {
res.setHeader(key, value);
}
res.end();
return;
}
// Origin check
if (corsMod.isDisallowedOrigin(webRequest)) {
res.statusCode = 403;
res.setHeader('Content-Type', 'application/json');
for (const [key, value] of Object.entries(corsHeaders)) {
res.setHeader(key, value);
}
res.end(JSON.stringify({ error: 'Origin not allowed' }));
return;
}
// Route matching
const matchedHandler = router.match(webRequest);
if (!matchedHandler) {
const allowed = router.allowedMethods(new URL(webRequest.url).pathname);
if (allowed.length > 0) {
res.statusCode = 405;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Allow', allowed.join(', '));
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'application/json');
}
for (const [key, value] of Object.entries(corsHeaders)) {
res.setHeader(key, value);
}
res.end(JSON.stringify({ error: res.statusCode === 405 ? 'Method not allowed' : 'Not found' }));
return;
}
// Execute handler
const response = await matchedHandler(webRequest);
// Write response
res.statusCode = response.status;
response.headers.forEach((value, key) => {
res.setHeader(key, value);
});
for (const [key, value] of Object.entries(corsHeaders)) {
res.setHeader(key, value);
}
res.end(await response.text());
} catch (err) {
console.error('[sebuf-api] Error:', err);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Internal server error' }));
}
});
},
};
}
function rssProxyPlugin(): Plugin {
return {
name: 'rss-proxy',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (!req.url?.startsWith('/api/rss-proxy')) {
return next();
}
const url = new URL(req.url, 'http://localhost');
const feedUrl = url.searchParams.get('url');
if (!feedUrl) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Missing url parameter' }));
return;
}
try {
const parsed = new URL(feedUrl);
if (!isAllowedDomain(parsed.hostname)) {
res.statusCode = 403;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: `Domain not allowed: ${parsed.hostname}` }));
return;
}
const controller = new AbortController();
const timeout = feedUrl.includes('news.google.com') ? 20000 : 12000;
const timer = setTimeout(() => controller.abort(), timeout);
const response = await fetch(feedUrl, {
signal: controller.signal,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/rss+xml, application/xml, text/xml, */*',
},
redirect: 'follow',
});
clearTimeout(timer);
const data = await response.text();
res.statusCode = response.status;
res.setHeader('Content-Type', 'application/xml');
res.setHeader('Cache-Control', 'public, max-age=300');
res.setHeader('Access-Control-Allow-Origin', '*');
res.end(data);
} catch (error: any) {
console.error('[rss-proxy]', feedUrl, error.message);
res.statusCode = error.name === 'AbortError' ? 504 : 502;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: error.name === 'AbortError' ? 'Feed timeout' : 'Failed to fetch feed' }));
}
});
},
};
}
function youtubeLivePlugin(): Plugin {
return {
name: 'youtube-live',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (!req.url?.startsWith('/api/youtube/live')) {
return next();
}
const url = new URL(req.url, 'http://localhost');
const channel = url.searchParams.get('channel');
if (!channel) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Missing channel parameter' }));
return;
}
try {
const channelHandle = channel.startsWith('@') ? channel : `@${channel}`;
const liveUrl = `https://www.youtube.com/${channelHandle}/live`;
const ytRes = await fetch(liveUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
},
redirect: 'follow',
});
if (!ytRes.ok) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'public, max-age=300');
res.end(JSON.stringify({ videoId: null, channel }));
return;
}
const html = await ytRes.text();
// Scope both fields to the same videoDetails block so we don't
// combine a videoId from one object with isLive from another.
let videoId: string | null = null;
const detailsIdx = html.indexOf('"videoDetails"');
if (detailsIdx !== -1) {
const block = html.substring(detailsIdx, detailsIdx + 5000);
const vidMatch = block.match(/"videoId":"([a-zA-Z0-9_-]{11})"/);
const liveMatch = block.match(/"isLive"\s*:\s*true/);
if (vidMatch && liveMatch) {
videoId = vidMatch[1];
}
}
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'public, max-age=300');
res.end(JSON.stringify({ videoId, isLive: videoId !== null, channel }));
} catch (error) {
console.error(`[YouTube Live] Error:`, error);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Failed to fetch', videoId: null }));
}
});
},
};
}
function gpsjamDevPlugin(): Plugin {
return {
name: 'gpsjam-dev',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (req.url !== '/api/gpsjam' && !req.url?.startsWith('/api/gpsjam?')) {
return next();
}
try {
const data = await readFile(resolve(__dirname, 'scripts/data/gpsjam-latest.json'), 'utf8');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.end(data);
} catch {
res.statusCode = 503;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.end(JSON.stringify({ error: 'No GPS jam data. Run: node scripts/fetch-gpsjam.mjs' }));
}
});
},
};
}
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
// Inject environment variables from .env files into process.env.
// This ensures that API keys and other secrets in .env.local are
// available to the dev server plugins and server-side handlers.
Object.assign(process.env, env);
// Dev-server port: DEV_PORT overrides the 3000 default. Reject non-integer or
// out-of-range values (fall back to 3000) so a typo can't crash Vite's listen()
// with ERR_SOCKET_BAD_PORT. Not VITE_-prefixed, so it never reaches the client bundle.
const parsedDevPort = Number(env.DEV_PORT);
const devPort =
Number.isInteger(parsedDevPort) && parsedDevPort >= 1 && parsedDevPort <= 65535
? parsedDevPort
: 3000;
const isE2E = process.env.VITE_E2E === '1';
const isDesktopBuild = process.env.VITE_DESKTOP_RUNTIME === '1';
const activeVariant = process.env.VITE_VARIANT || 'full';
const activeMeta = VARIANT_META[activeVariant] || VARIANT_META.full;
return {
html: {
cspNonce: STATIC_SCRIPT_NONCE,
},
define: {
__APP_VERSION__: JSON.stringify(pkg.version),
// Resolved + build-time validated above (devDependencies fallback +
// non-empty + major-pairing guards).
__CLERK_JS_VERSION__: JSON.stringify(CLERK_JS_VERSION),
// Vercel sets VERCEL_GIT_COMMIT_SHA on production + preview builds.
// Local `vite build` falls back to 'dev' — installStaleBundleCheck
// detects the marker and skips the comparison so dev tabs don't
// reload on every focus.
__BUILD_HASH__: JSON.stringify(process.env.VERCEL_GIT_COMMIT_SHA ?? 'dev'),
},
plugins: [
// Emit dist/build-hash.txt with the deployed SHA so the running bundle
// can fetch /build-hash.txt at tab-focus time and force-reload itself
// if it's running an older bundle (see src/bootstrap/stale-bundle-check.ts).
// Same-origin static asset, NOT under /api/* — installWebApiRedirect
// doesn't touch it, so the comparison reflects the web deployment.
{
name: 'wm-emit-build-hash',
apply: 'build',
generateBundle() {
this.emitFile({
type: 'asset',
fileName: 'build-hash.txt',
source: process.env.VERCEL_GIT_COMMIT_SHA ?? 'dev',
});
},
},
htmlVariantPlugin(activeMeta, activeVariant, isDesktopBuild),
!isDesktopBuild && dashboardHtmlOutputPlugin(),
// Variant subdomain SEO pages only make sense on the web deployment,
// which is always the 'full' build (variant selection is runtime by
// hostname). Desktop and dedicated VITE_VARIANT builds skip it.
!isDesktopBuild && activeVariant === 'full' && variantDashboardHtmlPlugin(),
polymarketPlugin(),
rssProxyPlugin(),
youtubeLivePlugin(),
gpsjamDevPlugin(),
sebufApiPlugin(),
brotliPrecompressPlugin(),
VitePWA({
registerType: 'autoUpdate',
injectRegister: false,
includeAssets: [
'favico/favicon.ico',
'favico/apple-touch-icon.png',
'favico/favicon-32x32.png',
],
// Manifest install icons stay advertised in manifest.webmanifest, but
// they are fetched on demand instead of forced into first-visit SW
// precache with the rest of the dashboard shell.
includeManifestIcons: false,
manifest: {
name: `${activeMeta.siteName} - ${activeMeta.subject}`,
short_name: activeMeta.shortName,
description: activeMeta.description,
start_url: '/dashboard',
scope: '/',
display: 'standalone',
orientation: 'any',
theme_color: '#0a0f0a',
background_color: '#0a0f0a',
categories: activeMeta.categories,
icons: [
{ src: '/favico/android-chrome-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: '/favico/android-chrome-512x512.png', sizes: '512x512', type: 'image/png' },
{ src: '/favico/android-chrome-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
},
workbox: {
globPatterns: ['**/*.{js,css,ico,png,svg,woff2}'],
globIgnores: [
'**/ml*.js',
'**/onnx*.wasm',
'**/locale-*.js',
'**/clerk-*.js',
// Fonts are fetched only when their stylesheet applies. Precache
// would pull every local weight into the first mobile visit.
'**/*.woff2',
// Keep off-page/static-heavy public assets out of the dashboard's
// first-visit precache. The small root favicons above remain
// explicit includeAssets entries.
'pro/**',
'favico/**',
'textures/**',
// #4891: blog OG covers + post images are generated into the prod
// build (absent locally), and the png glob was precaching all ~40
// of them (~700KB) on every first dashboard visit — and again on
// each SW update after a blog deploy. Blog pages fetch their own
// images on demand; the dashboard never needs them.
'blog/**',
],
// globe.gl + three.js grows main bundle past the 2 MiB default limit
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024,
navigateFallback: null,
skipWaiting: true,
clientsClaim: true,
cleanupOutdatedCaches: true,
// Web Push handler (Phase 6). importScripts runs in the SW
// context; /push-handler.js is a static file copied from
// public/ and attaches 'push' + 'notificationclick' listeners.
importScripts: ['/push-handler.js'],
runtimeCaching: [
{
urlPattern: ({ request }: { request: Request }) => request.mode === 'navigate',
handler: 'NetworkFirst',
options: {
cacheName: 'html-navigation',
networkTimeoutSeconds: 5,
cacheableResponse: { statuses: [200] },
},
},
{
urlPattern: ({ url, sameOrigin }: { url: URL; sameOrigin: boolean }) =>
sameOrigin && /^\/api\//.test(url.pathname),
handler: 'NetworkOnly',
method: 'GET',
},
{
urlPattern: ({ url, sameOrigin }: { url: URL; sameOrigin: boolean }) =>
sameOrigin && /^\/api\//.test(url.pathname),
handler: 'NetworkOnly',
method: 'POST',