gemi 0.203.0 → 0.204.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.
- package/dist/ai/Agent.d.ts +20 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +5 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +52 -55
- package/dist/ai/index.js.map +3 -13
- package/dist/ai/providers/request.d.ts +1 -0
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/testing/Fingerprints.d.ts +106 -0
- package/dist/ai/testing/Fingerprints.d.ts.map +1 -0
- package/dist/ai/testing/RecordingProvider.d.ts +258 -0
- package/dist/ai/testing/RecordingProvider.d.ts.map +1 -0
- package/dist/ai/testing/index.d.ts +4 -0
- package/dist/ai/testing/index.d.ts.map +1 -0
- package/dist/ai/testing/index.js +6 -0
- package/dist/ai/testing/index.js.map +12 -0
- package/dist/ai/testing/pinClock.d.ts +19 -0
- package/dist/ai/testing/pinClock.d.ts.map +1 -0
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/bun/plugin.js +2 -2
- package/dist/bun/plugin.js.map +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +1 -1
- package/dist/{chunk-dj9nspcw.js → chunk-0hfzzb3k.js} +3 -3
- package/dist/{chunk-dj9nspcw.js.map → chunk-0hfzzb3k.js.map} +1 -1
- package/dist/chunk-0pgk811s.js +4 -0
- package/dist/{chunk-3e19n0f2.js.map → chunk-0pgk811s.js.map} +2 -2
- package/dist/{chunk-2fbsd1b0.js → chunk-0shq2d31.js} +2 -2
- package/dist/{chunk-2fbsd1b0.js.map → chunk-0shq2d31.js.map} +1 -1
- package/dist/{chunk-wfwpjx25.js → chunk-0t1d9s34.js} +3 -3
- package/dist/{chunk-wfwpjx25.js.map → chunk-0t1d9s34.js.map} +1 -1
- package/dist/{chunk-hergje99.js → chunk-1e82gfk9.js} +3 -3
- package/dist/{chunk-hergje99.js.map → chunk-1e82gfk9.js.map} +1 -1
- package/dist/{chunk-95re1b2y.js → chunk-1kehwa3s.js} +1 -1
- package/dist/chunk-1x60thpm.js +8 -0
- package/dist/chunk-1x60thpm.js.map +19 -0
- package/dist/{chunk-px2a83jv.js → chunk-2ngdhbz7.js} +2 -2
- package/dist/{chunk-px2a83jv.js.map → chunk-2ngdhbz7.js.map} +1 -1
- package/dist/{chunk-5dhp90cx.js → chunk-2t1eyzvq.js} +2 -2
- package/dist/{chunk-5dhp90cx.js.map → chunk-2t1eyzvq.js.map} +1 -1
- package/dist/{chunk-ggmznkqs.js → chunk-39hed4yr.js} +3 -3
- package/dist/{chunk-ggmznkqs.js.map → chunk-39hed4yr.js.map} +1 -1
- package/dist/{chunk-tgbj942e.js → chunk-3gkxnfef.js} +3 -3
- package/dist/{chunk-tgbj942e.js.map → chunk-3gkxnfef.js.map} +1 -1
- package/dist/{chunk-k3m1wr1c.js → chunk-3xzhbkya.js} +3 -3
- package/dist/{chunk-k3m1wr1c.js.map → chunk-3xzhbkya.js.map} +1 -1
- package/dist/{chunk-95cs3r49.js → chunk-4c0rb2ng.js} +2 -2
- package/dist/{chunk-95cs3r49.js.map → chunk-4c0rb2ng.js.map} +1 -1
- package/dist/chunk-4ex4s616.js +4 -0
- package/dist/{chunk-tkskgvhc.js.map → chunk-4ex4s616.js.map} +2 -2
- package/dist/{chunk-n5g9a48h.js → chunk-4m8t67px.js} +2 -2
- package/dist/{chunk-n5g9a48h.js.map → chunk-4m8t67px.js.map} +1 -1
- package/dist/{chunk-1hpedme7.js → chunk-4v5c4mes.js} +2 -2
- package/dist/{chunk-1hpedme7.js.map → chunk-4v5c4mes.js.map} +1 -1
- package/dist/{chunk-g5j5hx6a.js → chunk-5gvc03cv.js} +3 -3
- package/dist/{chunk-g5j5hx6a.js.map → chunk-5gvc03cv.js.map} +1 -1
- package/dist/{chunk-r842yxd9.js → chunk-5km0np8s.js} +2 -2
- package/dist/{chunk-r842yxd9.js.map → chunk-5km0np8s.js.map} +1 -1
- package/dist/{chunk-m3xvm2va.js → chunk-6bfj0mbp.js} +3 -3
- package/dist/{chunk-m3xvm2va.js.map → chunk-6bfj0mbp.js.map} +1 -1
- package/dist/chunk-6g1xac70.js +7 -0
- package/dist/chunk-6g1xac70.js.map +10 -0
- package/dist/{chunk-kmpxda7j.js → chunk-6w6q9mxe.js} +3 -3
- package/dist/{chunk-kmpxda7j.js.map → chunk-6w6q9mxe.js.map} +2 -2
- package/dist/chunk-733e6v7b.js +6 -0
- package/dist/{chunk-z97tptd1.js.map → chunk-733e6v7b.js.map} +2 -2
- package/dist/{chunk-dyb649h3.js → chunk-77x9vxht.js} +3 -3
- package/dist/{chunk-dyb649h3.js.map → chunk-77x9vxht.js.map} +1 -1
- package/dist/{chunk-5q2tt76t.js → chunk-7gxmf9rg.js} +2 -2
- package/dist/{chunk-5q2tt76t.js.map → chunk-7gxmf9rg.js.map} +1 -1
- package/dist/{chunk-vyp7d7xz.js → chunk-8jfnn7v6.js} +2 -2
- package/dist/{chunk-vyp7d7xz.js.map → chunk-8jfnn7v6.js.map} +1 -1
- package/dist/{chunk-zvhks9s7.js → chunk-8pw4zjnx.js} +1 -1
- package/dist/{chunk-9q5xhb64.js → chunk-9bjggtdt.js} +2 -2
- package/dist/{chunk-9q5xhb64.js.map → chunk-9bjggtdt.js.map} +1 -1
- package/dist/{chunk-rwe4bgt3.js → chunk-9hqnecjt.js} +2 -2
- package/dist/{chunk-rwe4bgt3.js.map → chunk-9hqnecjt.js.map} +1 -1
- package/dist/{chunk-s0z61m9j.js → chunk-9m7c4mws.js} +2 -2
- package/dist/{chunk-s0z61m9j.js.map → chunk-9m7c4mws.js.map} +1 -1
- package/dist/{chunk-r02em4jv.js → chunk-b1mdan5a.js} +2 -2
- package/dist/{chunk-r02em4jv.js.map → chunk-b1mdan5a.js.map} +1 -1
- package/dist/chunk-b9czfrxm.js +24 -0
- package/dist/{chunk-70qqpvd9.js.map → chunk-b9czfrxm.js.map} +2 -2
- package/dist/{chunk-7txst143.js → chunk-bq4pgzcd.js} +2 -2
- package/dist/{chunk-7txst143.js.map → chunk-bq4pgzcd.js.map} +1 -1
- package/dist/chunk-c7nbzryd.js +9 -0
- package/dist/chunk-c7nbzryd.js.map +10 -0
- package/dist/{chunk-pp34d463.js → chunk-cdgnwzwf.js} +2 -2
- package/dist/{chunk-pp34d463.js.map → chunk-cdgnwzwf.js.map} +1 -1
- package/dist/chunk-cf7xc02m.js +5 -0
- package/dist/{chunk-9mhr0kwd.js.map → chunk-cf7xc02m.js.map} +1 -1
- package/dist/{chunk-2nw8rf5y.js → chunk-cq7hk8v9.js} +2 -2
- package/dist/{chunk-2nw8rf5y.js.map → chunk-cq7hk8v9.js.map} +1 -1
- package/dist/{chunk-8m9kgynj.js → chunk-crqbzfd5.js} +2 -2
- package/dist/{chunk-8m9kgynj.js.map → chunk-crqbzfd5.js.map} +1 -1
- package/dist/{chunk-vee6v6qf.js → chunk-d3k38gk1.js} +3 -3
- package/dist/{chunk-vee6v6qf.js.map → chunk-d3k38gk1.js.map} +1 -1
- package/dist/{chunk-41fqkygr.js → chunk-d5d3a8bm.js} +3 -3
- package/dist/{chunk-41fqkygr.js.map → chunk-d5d3a8bm.js.map} +1 -1
- package/dist/chunk-d7kknkmq.js +13 -0
- package/dist/{chunk-4fw84bh6.js.map → chunk-d7kknkmq.js.map} +3 -4
- package/dist/{chunk-ke7d7j2y.js → chunk-dk1xxtgk.js} +2 -2
- package/dist/{chunk-ke7d7j2y.js.map → chunk-dk1xxtgk.js.map} +1 -1
- package/dist/{chunk-nqg7hdy8.js → chunk-e3ehv27z.js} +3 -3
- package/dist/{chunk-nqg7hdy8.js.map → chunk-e3ehv27z.js.map} +1 -1
- package/dist/{chunk-se58ty45.js → chunk-e5mqjren.js} +4 -4
- package/dist/{chunk-se58ty45.js.map → chunk-e5mqjren.js.map} +2 -2
- package/dist/{chunk-t91x2k88.js → chunk-efnerp0c.js} +2 -2
- package/dist/{chunk-t91x2k88.js.map → chunk-efnerp0c.js.map} +1 -1
- package/dist/{chunk-ys4q1jg2.js → chunk-ek0dvbck.js} +3 -3
- package/dist/{chunk-ys4q1jg2.js.map → chunk-ek0dvbck.js.map} +1 -1
- package/dist/{chunk-a4twd6qh.js → chunk-ezvtkbp9.js} +2 -2
- package/dist/{chunk-a4twd6qh.js.map → chunk-ezvtkbp9.js.map} +1 -1
- package/dist/{chunk-h19qtrg9.js → chunk-f52maa9b.js} +2 -2
- package/dist/{chunk-h19qtrg9.js.map → chunk-f52maa9b.js.map} +1 -1
- package/dist/{chunk-nfbf388w.js → chunk-f9c8bnzx.js} +3 -3
- package/dist/{chunk-nfbf388w.js.map → chunk-f9c8bnzx.js.map} +2 -2
- package/dist/{chunk-bwg7genv.js → chunk-fq5b1k4n.js} +2 -2
- package/dist/{chunk-bwg7genv.js.map → chunk-fq5b1k4n.js.map} +1 -1
- package/dist/{chunk-dvw8cr6n.js → chunk-gc9g7c4p.js} +3 -3
- package/dist/{chunk-dvw8cr6n.js.map → chunk-gc9g7c4p.js.map} +1 -1
- package/dist/{chunk-sq5ytcpd.js → chunk-jeq8wvj6.js} +2 -2
- package/dist/{chunk-sq5ytcpd.js.map → chunk-jeq8wvj6.js.map} +1 -1
- package/dist/{chunk-vw57atx4.js → chunk-jma5d7zd.js} +3 -3
- package/dist/{chunk-vw57atx4.js.map → chunk-jma5d7zd.js.map} +1 -1
- package/dist/{chunk-nsxw6v2b.js → chunk-jmsfkzav.js} +2 -2
- package/dist/{chunk-nsxw6v2b.js.map → chunk-jmsfkzav.js.map} +1 -1
- package/dist/chunk-js9rm7g0.js +4 -0
- package/dist/{chunk-02s440vh.js.map → chunk-js9rm7g0.js.map} +2 -2
- package/dist/{chunk-6t9n4qdm.js → chunk-k1gt7fgy.js} +3 -3
- package/dist/{chunk-6t9n4qdm.js.map → chunk-k1gt7fgy.js.map} +1 -1
- package/dist/{chunk-cbmne0wt.js → chunk-k62338g2.js} +2 -2
- package/dist/{chunk-cbmne0wt.js.map → chunk-k62338g2.js.map} +1 -1
- package/dist/{chunk-05k9201j.js → chunk-k9882kqg.js} +2 -2
- package/dist/{chunk-05k9201j.js.map → chunk-k9882kqg.js.map} +1 -1
- package/dist/{chunk-bzaespn5.js → chunk-n26atakz.js} +3 -3
- package/dist/{chunk-bzaespn5.js.map → chunk-n26atakz.js.map} +1 -1
- package/dist/{chunk-vbdy4k14.js → chunk-n3kg99yw.js} +3 -3
- package/dist/{chunk-vbdy4k14.js.map → chunk-n3kg99yw.js.map} +1 -1
- package/dist/{chunk-c6v3sjvh.js → chunk-n5k42dh7.js} +3 -3
- package/dist/{chunk-c6v3sjvh.js.map → chunk-n5k42dh7.js.map} +1 -1
- package/dist/chunk-p2nqksdq.js +10 -0
- package/dist/{chunk-ht5mq6ev.js.map → chunk-p2nqksdq.js.map} +2 -2
- package/dist/{chunk-mvd4mc8p.js → chunk-p9pwskv6.js} +2 -2
- package/dist/{chunk-mvd4mc8p.js.map → chunk-p9pwskv6.js.map} +1 -1
- package/dist/{chunk-14dtbk7d.js → chunk-phvvxv1a.js} +3 -3
- package/dist/{chunk-14dtbk7d.js.map → chunk-phvvxv1a.js.map} +1 -1
- package/dist/chunk-pq15dt8j.js +46 -0
- package/dist/chunk-pq15dt8j.js.map +27 -0
- package/dist/{chunk-q05648ac.js → chunk-ptpzh61m.js} +3 -3
- package/dist/{chunk-q05648ac.js.map → chunk-ptpzh61m.js.map} +1 -1
- package/dist/{chunk-nkasdjx2.js → chunk-qcrj4t72.js} +3 -3
- package/dist/{chunk-nkasdjx2.js.map → chunk-qcrj4t72.js.map} +1 -1
- package/dist/{chunk-bfhcx1ca.js → chunk-re9ac4tc.js} +27 -27
- package/dist/{chunk-bfhcx1ca.js.map → chunk-re9ac4tc.js.map} +7 -6
- package/dist/{chunk-q093ph67.js → chunk-rr8bzm6k.js} +2 -2
- package/dist/{chunk-q093ph67.js.map → chunk-rr8bzm6k.js.map} +1 -1
- package/dist/{chunk-gm34n6da.js → chunk-s5hdrpam.js} +3 -3
- package/dist/{chunk-gm34n6da.js.map → chunk-s5hdrpam.js.map} +1 -1
- package/dist/{chunk-k0220nam.js → chunk-s6bq91cm.js} +2 -2
- package/dist/{chunk-k0220nam.js.map → chunk-s6bq91cm.js.map} +1 -1
- package/dist/{chunk-gz2ekvd6.js → chunk-s6wj8e56.js} +2 -2
- package/dist/{chunk-gz2ekvd6.js.map → chunk-s6wj8e56.js.map} +2 -2
- package/dist/{chunk-vt0vybw8.js → chunk-vsd5h2d9.js} +3 -3
- package/dist/{chunk-vt0vybw8.js.map → chunk-vsd5h2d9.js.map} +1 -1
- package/dist/{chunk-a1cwr0wh.js → chunk-w3mc696j.js} +2 -2
- package/dist/{chunk-a1cwr0wh.js.map → chunk-w3mc696j.js.map} +1 -1
- package/dist/{chunk-811qpkzd.js → chunk-wn4j741t.js} +2 -2
- package/dist/{chunk-811qpkzd.js.map → chunk-wn4j741t.js.map} +1 -1
- package/dist/{chunk-xmy09pr9.js → chunk-wxyxnbh6.js} +4 -4
- package/dist/{chunk-xmy09pr9.js.map → chunk-wxyxnbh6.js.map} +1 -1
- package/dist/{chunk-tp37k8c0.js → chunk-x244kqcc.js} +2 -2
- package/dist/{chunk-tp37k8c0.js.map → chunk-x244kqcc.js.map} +1 -1
- package/dist/chunk-x26jb60f.js +4 -0
- package/dist/{chunk-z7wchajg.js.map → chunk-x26jb60f.js.map} +2 -2
- package/dist/{chunk-4ehzm7p1.js → chunk-xvk6aqd7.js} +3 -3
- package/dist/{chunk-4ehzm7p1.js.map → chunk-xvk6aqd7.js.map} +1 -1
- package/dist/chunk-xwqdh388.js +5 -0
- package/dist/chunk-xwqdh388.js.map +13 -0
- package/dist/{chunk-56b6m0d4.js → chunk-y45whafz.js} +2 -2
- package/dist/{chunk-56b6m0d4.js.map → chunk-y45whafz.js.map} +1 -1
- package/dist/{chunk-q8a7ncvs.js → chunk-y5kfqq4f.js} +2 -2
- package/dist/{chunk-q8a7ncvs.js.map → chunk-y5kfqq4f.js.map} +1 -1
- package/dist/chunk-ybcdxrqx.js +4 -0
- package/dist/{chunk-wqphnrej.js.map → chunk-ybcdxrqx.js.map} +2 -2
- package/dist/{chunk-7nmbzdys.js → chunk-yrbvfda9.js} +1 -1
- package/dist/{chunk-wc3q88a2.js → chunk-yykrvrpt.js} +1 -1
- package/dist/{chunk-fxvqtwte.js → chunk-zk1vwwv6.js} +2 -2
- package/dist/{chunk-fxvqtwte.js.map → chunk-zk1vwwv6.js.map} +1 -1
- package/dist/chunks/{RealtimeClient-BnNSz8AK.js → RealtimeClient-CLXePUcE.js} +2 -2
- package/dist/chunks/{RealtimeClient-BnNSz8AK.js.map → RealtimeClient-CLXePUcE.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-CoQ-vnvy.js → ThemeProvider-COjYIalw.js} +74 -1273
- package/dist/chunks/ThemeProvider-COjYIalw.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-Bhp0oJ0T.js → fetchFileRequest-BaufNZpI.js} +2 -2
- package/dist/chunks/{fetchFileRequest-Bhp0oJ0T.js.map → fetchFileRequest-BaufNZpI.js.map} +1 -1
- package/dist/chunks/{live-Dt8sq9W4.js → live-Dz_rk7fm.js} +4 -15
- package/dist/chunks/{live-Dt8sq9W4.js.map → live-Dz_rk7fm.js.map} +1 -1
- package/dist/chunks/{mutationExtras-ChOGPZlY.js → mutationExtras-DtSw6BcX.js} +2 -2
- package/dist/chunks/{mutationExtras-ChOGPZlY.js.map → mutationExtras-DtSw6BcX.js.map} +1 -1
- package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/chunks/{subscriptionStream-DDl_H-QM.js → subscriptionStream-CqhJOfPn.js} +2 -2
- package/dist/chunks/{subscriptionStream-DDl_H-QM.js.map → subscriptionStream-CqhJOfPn.js.map} +1 -1
- package/dist/chunks/urlpattern-polyfill-Cc7YrzJf.js +913 -0
- package/dist/chunks/urlpattern-polyfill-Cc7YrzJf.js.map +1 -0
- package/dist/client/ClientRouter.d.ts +1 -1
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/ClientRouterContext.d.ts +1 -1
- package/dist/client/ClientRouterContext.d.ts.map +1 -1
- package/dist/client/browserHistory.d.ts +13 -0
- package/dist/client/browserHistory.d.ts.map +1 -0
- package/dist/client/index.js +9 -6
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts.map +1 -1
- package/dist/client/scrollRestoration.d.ts +1 -1
- package/dist/client/scrollRestoration.d.ts.map +1 -1
- package/dist/client/urlPattern.d.ts +30 -0
- package/dist/client/urlPattern.d.ts.map +1 -0
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/DB.d.ts +10 -0
- package/dist/facades/DB.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +2 -2
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +2 -2
- package/dist/orm/Model.d.ts.map +1 -1
- package/dist/orm/context.d.ts +54 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.d.ts +1 -1
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +4 -4
- package/dist/orm/index.js.map +3 -3
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +1 -0
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +234 -2
- package/dist/testing/index.js.map +1 -1
- package/dist/vitest/index.js +2 -2
- package/dist/vitest/index.js.map +1 -1
- package/package.json +2 -1
- package/dist/chunk-02s440vh.js +0 -4
- package/dist/chunk-3e19n0f2.js +0 -4
- package/dist/chunk-4fw84bh6.js +0 -15
- package/dist/chunk-70qqpvd9.js +0 -24
- package/dist/chunk-9mhr0kwd.js +0 -5
- package/dist/chunk-ht5mq6ev.js +0 -10
- package/dist/chunk-rczmh97n.js +0 -9
- package/dist/chunk-rczmh97n.js.map +0 -10
- package/dist/chunk-tkskgvhc.js +0 -4
- package/dist/chunk-v325k8qj.js +0 -46
- package/dist/chunk-v325k8qj.js.map +0 -31
- package/dist/chunk-wqphnrej.js +0 -4
- package/dist/chunk-z7wchajg.js +0 -4
- package/dist/chunk-z97tptd1.js +0 -6
- package/dist/chunks/ThemeProvider-CoQ-vnvy.js.map +0 -1
- /package/dist/{chunk-95re1b2y.js.map → chunk-1kehwa3s.js.map} +0 -0
- /package/dist/{chunk-zvhks9s7.js.map → chunk-8pw4zjnx.js.map} +0 -0
- /package/dist/{chunk-7nmbzdys.js.map → chunk-yrbvfda9.js.map} +0 -0
- /package/dist/{chunk-wc3q88a2.js.map → chunk-yykrvrpt.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../services/broadcast/channels.ts","../../client/realtime/FakeSocket.ts","../../testing/Page.tsx","../../internal/islandRuntime.ts","../../internal/staticNavigationRuntime.ts","../../testing/staticDocument.ts"],"sourcesContent":["/**\n * Channel names: patterns, the topics they build, and the checks both go\n * through. Shared by the `Broadcast` facade (which builds the topic an emit\n * goes to), `ChannelRouter` (which builds the topic a socket may join) and the\n * fake (which matches a pattern against recorded topics), so the three can\n * never disagree on what `site.:siteId` with `{ siteId: \"abc\" }` is called.\n *\n * A pattern is dot-separated segments, each either a literal (`site`) or a\n * param (`:siteId`). A topic is the same with every param filled in:\n * `site.abc123`. Param values are restricted to `[A-Za-z0-9_-]`, so a value\n * can never contain a dot and add a segment, and a topic can always be read\n * back as exactly one pattern's.\n */\n\n/** The longest topic, in characters. */\nexport const MAX_TOPIC_LENGTH = 255;\n\n/** The longest event name, in characters. */\nexport const MAX_EVENT_NAME_LENGTH = 64;\n\nconst LITERAL_SEGMENT = /^[A-Za-z0-9_-]+$/;\nconst PARAM_SEGMENT = /^:[A-Za-z_][A-Za-z0-9_]*$/;\nconst PARAM_VALUE = /^[A-Za-z0-9_-]{1,128}$/;\nconst EVENT_NAME = /^[A-Za-z0-9_.:-]+$/;\n\n/** The names of a pattern's params: `\"site.:siteId\"` → `\"siteId\"`. */\nexport type ChannelParamNames<P extends string> = P extends `${infer Head}.${infer Rest}`\n ? SegmentParam<Head> | ChannelParamNames<Rest>\n : SegmentParam<P>;\n\ntype SegmentParam<S extends string> = S extends `:${infer Name}` ? Name : never;\n\n/** The params a pattern takes: `\"site.:siteId\"` → `{ siteId: string | number }`. */\nexport type ChannelParams<P extends string> = {\n [K in ChannelParamNames<P>]: string | number;\n};\n\n/**\n * `[]` for a pattern without params (or a concrete topic), `[params]` for one\n * with them, so `Broadcast.to(\"status\")` and `Broadcast.to(\"site.:siteId\",\n * { siteId })` both type-check and `Broadcast.to(\"site.:siteId\")` does not.\n */\nexport type ChannelParamsArgs<P extends string> = [ChannelParamNames<P>] extends [never]\n ? [params?: Record<string, never>]\n : [params: ChannelParams<P>];\n\n/**\n * A resolved channel: the topic sockets subscribe to, and the pattern it came\n * from when it was built from one. What `BroadcastEvent.channel()` returns and\n * `Broadcast.to()` accepts.\n */\nexport interface ChannelTarget {\n readonly topic: string;\n readonly pattern?: string;\n}\n\n/** A pattern, topic or param was refused. The message says which and why. */\nexport class InvalidChannelError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidChannelError\";\n }\n}\n\n/** Whether `value` is a `ChannelTarget` rather than a pattern string. */\nexport function isChannelTarget(value: unknown): value is ChannelTarget {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { topic?: unknown }).topic === \"string\"\n );\n}\n\n/** The segments of a pattern, checked. Throws `InvalidChannelError`. */\nexport function parsePattern(pattern: string): string[] {\n if (typeof pattern !== \"string\" || pattern.length === 0) {\n throw new InvalidChannelError(\"A channel pattern must be a non-empty string.\");\n }\n if (pattern.length > MAX_TOPIC_LENGTH) {\n throw new InvalidChannelError(\n `The channel pattern \"${pattern.slice(0, 40)}…\" is longer than ${MAX_TOPIC_LENGTH} characters.`,\n );\n }\n const segments = pattern.split(\".\");\n const seen = new Set<string>();\n for (const segment of segments) {\n if (PARAM_SEGMENT.test(segment)) {\n const name = segment.slice(1);\n if (seen.has(name)) {\n throw new InvalidChannelError(\n `The channel pattern \"${pattern}\" names the param \"${name}\" twice.`,\n );\n }\n seen.add(name);\n continue;\n }\n if (segment.startsWith(\"__\")) {\n throw new InvalidChannelError(\n `The channel \"${pattern}\" has the segment \"${segment}\". Segments starting ` +\n `with \"__\" are reserved for gemi (driver control messages).`,\n );\n }\n if (!LITERAL_SEGMENT.test(segment)) {\n throw new InvalidChannelError(\n `The channel pattern \"${pattern}\" has an invalid segment \"${segment}\". ` +\n `Segments are separated by dots and are either letters, digits, \"_\" ` +\n `and \"-\", or a param such as \":siteId\".`,\n );\n }\n }\n return segments;\n}\n\n/** The param names of a pattern, in order. */\nexport function patternParams(pattern: string): string[] {\n return parsePattern(pattern)\n .filter((segment) => segment.startsWith(\":\"))\n .map((segment) => segment.slice(1));\n}\n\n/**\n * The topic `pattern` names with `params` filled in. Every param must be\n * given, and nothing else: a missing one, an extra one, or a value outside\n * `[A-Za-z0-9_-]` throws `InvalidChannelError`, so a client can never steer a\n * subscription onto a topic its pattern does not describe.\n */\nexport function buildTopic(pattern: string, params: Record<string, unknown> = {}): string {\n const segments = parsePattern(pattern);\n const expected = new Set<string>();\n const topic = segments\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n const name = segment.slice(1);\n expected.add(name);\n const value = params[name];\n if (value === undefined || value === null) {\n throw new InvalidChannelError(`The channel \"${pattern}\" needs the param \"${name}\".`);\n }\n const text = typeof value === \"number\" && Number.isFinite(value) ? String(value) : value;\n if (typeof text !== \"string\" || !PARAM_VALUE.test(text)) {\n throw new InvalidChannelError(\n `The param \"${name}\" of the channel \"${pattern}\" must be 1 to 128 ` +\n `letters, digits, \"_\" or \"-\". Use a public id in a channel name.`,\n );\n }\n return text;\n })\n .join(\".\");\n\n for (const key of Object.keys(params)) {\n if (!expected.has(key)) {\n throw new InvalidChannelError(`The channel \"${pattern}\" has no param \"${key}\".`);\n }\n }\n if (topic.length > MAX_TOPIC_LENGTH) {\n throw new InvalidChannelError(\n `The topic built from \"${pattern}\" is longer than ${MAX_TOPIC_LENGTH} characters.`,\n );\n }\n return topic;\n}\n\n/** Checks a concrete topic (no params). Throws `InvalidChannelError`. */\nexport function assertTopic(topic: string): string {\n const segments = parsePattern(topic);\n if (segments.some((segment) => segment.startsWith(\":\"))) {\n throw new InvalidChannelError(\n `\"${topic}\" is a pattern, not a topic: pass its params, as in ` +\n `Broadcast.to(\"${topic}\", { ... }).`,\n );\n }\n return topic;\n}\n\n/** Checks an event name. Throws `InvalidChannelError`. */\nexport function assertEventName(event: string): string {\n if (\n typeof event !== \"string\" ||\n event.length === 0 ||\n event.length > MAX_EVENT_NAME_LENGTH ||\n !EVENT_NAME.test(event)\n ) {\n throw new InvalidChannelError(\n `The event name \"${String(event).slice(0, 40)}\" must be 1 to ` +\n `${MAX_EVENT_NAME_LENGTH} letters, digits, \"_\", \"-\", \".\" or \":\".`,\n );\n }\n return event;\n}\n\n/**\n * Whether `topic` is one `pattern` builds. A pattern without params matches\n * only itself, except `\"user\"`, which also matches every `user.<id>`: that is\n * the topic the router's `user` channel resolves to.\n */\nexport function topicMatches(pattern: string, topic: string): boolean {\n if (pattern === topic) return true;\n if (pattern === USER_CHANNEL)\n return topic.startsWith(`${USER_CHANNEL}.`) && topic.split(\".\").length === 2;\n const patternSegments = pattern.split(\".\");\n const topicSegments = topic.split(\".\");\n if (patternSegments.length !== topicSegments.length) return false;\n return patternSegments.every(\n (segment, i) =>\n segment === topicSegments[i] ||\n (segment.startsWith(\":\") && PARAM_VALUE.test(topicSegments[i])),\n );\n}\n\n/**\n * The channel `ChannelRouter` resolves from the session rather than from\n * params: a socket that subscribes to `\"user\"` joins `user.<its user's id>`.\n */\nexport const USER_CHANNEL = \"user\";\n\n/** The topic of a user's own channel. */\nexport function userTopic(user: { id: unknown } | string | number): string {\n const id = typeof user === \"object\" && user !== null ? user.id : user;\n return buildTopic(`${USER_CHANNEL}.:id`, { id: id as string | number });\n}\n","import { buildTopic, topicMatches } from \"../../services/broadcast/channels\";\nimport type { DeniedCode } from \"../../services/broadcast/protocol\";\nimport { channelKey } from \"./channelKey\";\nimport type {\n ChannelListener,\n ChannelParamValues,\n ChannelStatus,\n RealtimeSocket,\n} from \"./RealtimeClient\";\n\nexport interface FakeSubscription {\n pattern: string;\n params: ChannelParamValues;\n status: ChannelStatus;\n code: DeniedCode | null;\n}\n\ninterface FakeEntry extends FakeSubscription {\n key: string;\n listeners: Set<ChannelListener>;\n}\n\n/**\n * A socket for component tests: what `<Page socket={...}>` hands the\n * channel hooks instead of a WebSocket. Every subscription is `open` at\n * once; the test pushes events and resyncs by hand.\n *\n * ```tsx\n * const socket = fakeSocket();\n * render(<Page socket={socket}><SiteEditor /></Page>);\n * act(() => socket.emit(\"site.:siteId\", \"changed\", { pages: [\"/about\"] }));\n * act(() => socket.resync());\n * ```\n *\n * No resync is run on subscribe, unlike the real socket's ack: a test says\n * when one happens.\n */\nexport class FakeSocket implements RealtimeSocket {\n private entries = new Map<string, FakeEntry>();\n private status: ChannelStatus = \"open\";\n\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void {\n const key = channelKey(pattern, params);\n let entry = this.entries.get(key);\n if (!entry) {\n entry = {\n key,\n pattern,\n params: { ...params },\n status: this.status,\n code: null,\n listeners: new Set(),\n };\n this.entries.set(key, entry);\n }\n entry.listeners.add(listener);\n listener.onStatus?.(entry.status, entry.code);\n return () => {\n entry!.listeners.delete(listener);\n if (entry!.listeners.size === 0) this.entries.delete(key);\n };\n }\n\n /** The channels subscribed to right now. */\n get subscriptions(): FakeSubscription[] {\n return Array.from(this.entries.values()).map(({ pattern, params, status, code }) => ({\n pattern,\n params,\n status,\n code,\n }));\n }\n\n /**\n * Delivers `event` to the open subscriptions `channel` names: a pattern\n * (`\"site.:siteId\"`, every subscription to it, or only those with `params`\n * when given), or a concrete topic (`\"site.abc\"`).\n */\n emit(channel: string, event: string, data?: unknown, params?: ChannelParamValues): void {\n for (const entry of this.matching(channel, params)) {\n if (entry.status !== \"open\") continue;\n for (const listener of Array.from(entry.listeners)) listener.onEvent?.(event, data);\n }\n }\n\n /** Runs every matching subscription's resync (all when `channel` is left out). */\n resync(channel?: string, params?: ChannelParamValues): void {\n for (const entry of channel ? this.matching(channel, params) : this.entries.values()) {\n if (entry.status !== \"open\") continue;\n for (const listener of Array.from(entry.listeners)) listener.onResync?.();\n }\n }\n\n /** Sets every subscription's status (and the status new ones start in). */\n setStatus(status: ChannelStatus): void {\n this.status = status;\n for (const entry of this.entries.values()) this.update(entry, status, null);\n }\n\n /** Refuses the matching subscriptions with `code`. */\n deny(channel: string, code: DeniedCode = \"denied\", params?: ChannelParamValues): void {\n for (const entry of this.matching(channel, params)) this.update(entry, \"denied\", code);\n }\n\n private update(entry: FakeEntry, status: ChannelStatus, code: DeniedCode | null) {\n entry.status = status;\n entry.code = code;\n for (const listener of Array.from(entry.listeners)) listener.onStatus?.(status, code);\n }\n\n private matching(channel: string, params?: ChannelParamValues): FakeEntry[] {\n return Array.from(this.entries.values()).filter((entry) => {\n if (entry.pattern === channel) {\n return !params || channelKey(channel, params) === entry.key;\n }\n try {\n const topic =\n Object.keys(entry.params).length > 0\n ? buildTopic(entry.pattern, entry.params)\n : entry.pattern;\n // `\"user\"` is resolved to `user.<id>` by the server; any id matches.\n return topic === channel || (entry.pattern === \"user\" && topicMatches(\"user\", channel));\n } catch {\n return false;\n }\n });\n }\n}\n\n/** A `FakeSocket` for `<Page socket={...}>`. */\nexport function fakeSocket(): FakeSocket {\n return new FakeSocket();\n}\n","import {\n Suspense,\n useContext,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type PropsWithChildren,\n type ReactNode,\n} from \"react\";\nimport { ErrorBoundary, type FallbackProps } from \"react-error-boundary\";\nimport { Action, createMemoryHistory } from \"history\";\n\nimport type { User } from \"../auth/types\";\nimport { ClientRouterContext } from \"../client/ClientRouterContext\";\nimport { I18nProvider } from \"../client/I18nContext\";\nimport { ProgressManager } from \"../client/ProgressManager\";\nimport {\n QueryManagerContext,\n QueryManagerProvider,\n type QueryConfig,\n} from \"../client/QueryManagerContext\";\nimport {\n RouteStateProvider,\n type PageData,\n type RouteState,\n} from \"../client/RouteStateContext\";\nimport { RouteTransitionProvider } from \"../client/RouteTransitionProvider\";\nimport {\n ServerDataContext,\n type ServerDataContextValue,\n} from \"../client/ServerDataProvider\";\nimport { ThemeProvider } from \"../client/ThemeProvider\";\nimport type { ClientFeatureKey } from \"../client/rpc\";\nimport { FakeSocket } from \"../client/realtime/FakeSocket\";\nimport { followLive } from \"../client/realtime/live\";\nimport { liveModule } from \"../client/realtime/loader\";\nimport { RealtimeContext } from \"../client/realtime/RealtimeContext\";\nimport type { Breadcrumb } from \"../client/useBreadcrumbs\";\nimport { applyParams } from \"../utils/applyParams\";\nimport { Subject } from \"../utils/Subject\";\nimport { toVariantKey } from \"../utils/variantKey\";\n\n// A live query loads its subscription on first use in an app (#891). Under\n// `<Page>` it is here already, so a query on the `FakeSocket` subscribes in\n// its effect and a test sees events without waiting for a module to load.\nliveModule.current = { followLive };\n\n/**\n * A dictionary as `Dictionary.create` produces it: a name and a\n * `{ key: { locale: string } }` map.\n *\n * Typed structurally rather than as `Dictionary<T>` for two reasons. It keeps\n * `gemi/testing` from importing `gemi/i18n` — a server entry, which reaches the\n * `Lang` facade and through it the container. And it means an object literal of\n * the same shape is accepted, so a test never *has* to import the app's\n * dictionaries at all.\n *\n * Only `name` and `dictionary` are read — both plain data. `Dictionary`'s\n * server-only methods (`render`, `reference`, which throw once `window` is\n * defined) are never called from here.\n */\nexport interface PageDictionary {\n name: string;\n dictionary: Record<string, Record<string, string>>;\n}\n\nexport interface PageProps {\n /**\n * The URL the view is mounted at. A template (`/app/:orgId/chat`) is resolved\n * against `params`, so the same string can be pasted from the router.\n *\n * As in the app, on a direct load and after a navigation alike,\n * `useRoute().pathname` reports the template as given here and\n * `useLocation().pathname` the resolved URL.\n */\n pathname?: string;\n /** Route params, as the router would have parsed them out of `pathname`. */\n params?: Record<string, string>;\n /** `\"?tab=recent\"`, `\"tab=recent\"`, or `{ tab: \"recent\" }`. */\n searchParams?: string | Record<string, string | number | boolean>;\n hash?: string;\n /** The locale `useTranslator` and `useLocale` report. */\n locale?: string;\n /**\n * The app's default locale. Links and `useNavigate` omit the locale segment\n * for it, so leaving this equal to `locale` (the default) keeps hrefs\n * unprefixed — set it to seed a page being viewed in a non-default locale.\n */\n defaultLocale?: string;\n supportedLocales?: string[];\n /** The zone `useFormatter` formats dates in. Defaults to `UTC`, like an app with no `translation.timeZone`. */\n timeZone?: string;\n /**\n * Dictionaries the components under test translate against — the app's own,\n * or literals of the same shape.\n *\n * Note what importing the app's costs: `app/i18n/index.ts` imports\n * `gemi/i18n`, a server entry, so the test file pulls the container and\n * `node:async_hooks` into its module graph. Nothing there runs (and nothing\n * here calls it), so it is fine under any runner that has Node builtins —\n * vitest, `bun test` — and not under one that renders in a real browser. Use\n * `translations` there, which is the shape the client actually receives.\n */\n dictionaries?: PageDictionary[];\n /**\n * Translations for the current locale, already resolved: dictionary name →\n * key → string. This is the shape the server serializes onto the page, so it\n * is what the client reads at runtime — and it imports nothing.\n *\n * ```tsx\n * <Page translations={{ Chat: { greeting: \"Hello {{name}}\" } }}>\n * ```\n *\n * Merged over `dictionaries`, so the two compose: seed from the app's real\n * dictionary and override the one key a test is about.\n */\n translations?: Record<string, Record<string, string>>;\n /**\n * Data `useQuery` finds already cached, keyed by API path — the path passed\n * to `useQuery`, without the `/api` prefix the client adds when it fetches.\n * A key may carry a query string (`\"/lists?page=2\"`) to seed one search\n * variant.\n *\n * The cache is keyed by the *resolved* path, so a key's `:params` are\n * resolved against the page's `params` — and a key naming one the page does\n * not carry is an error, naming the key. That case is common enough to be\n * worth the loud failure: a query often takes its params from the call site\n * rather than the route (`useQuery(\"/orgs/:orgId/lists\", { params: { orgId } })`\n * with `orgId` in component state), and the right seed for it is the resolved\n * path, `\"/orgs/abc/lists\"`.\n *\n * Seeded at mount only: a component that mutates or refetches its data owns\n * the cache from then on.\n */\n queryData?: Record<string, unknown>;\n /** App-wide `useQuery` defaults, as `createRoot` threads them. */\n queryConfig?: QueryConfig;\n /**\n * What `useUser()` reports. Defaults to `null` — an anonymous visitor — and\n * either way the hook resolves from here without issuing a request.\n */\n user?: Partial<User> | null;\n /** What `useBreadcrumbs()` returns, in order. */\n breadcrumbs?: Breadcrumb[];\n /**\n * The `route.domains` group the page is served under, as `useDomain()`\n * reports it. Left out, `useDomain()` reads empty — the shape an app without\n * `route.domains` sees — and `useDomain().url()` throws, exactly as it does\n * there.\n *\n * `root` and `origin` default off the host, so the common case is one field:\n * `domain={{ host: \"acme.example.com\", params: { tenant: \"acme\" } }}`.\n */\n domain?: {\n host: string;\n group?: string;\n params?: Record<string, string>;\n custom?: boolean;\n root?: string;\n origin?: string;\n } | null;\n /**\n * What `useFeature()` reports, keyed by feature key. Anything left out reads\n * as off, exactly as an undeclared key does in a real request.\n *\n * A test seeds the *outcome*, not the declaration: `app/features` owns the\n * targeting and the rollout, and re-deriving those here would mean building a\n * request context — a user, a `session_id`, a bot verdict — to assert a\n * branch that only cares which way the feature came out. Cover the targeting\n * where it lives, with a server test.\n */\n features?: Partial<Record<ClientFeatureKey, boolean>>;\n /**\n * The theme `useTheme()` starts on. The app reads a visitor's stored choice\n * out of `localStorage`; a test has no session to have made one in, so this\n * seeds it without writing to storage. `setTheme` works from either.\n */\n theme?: \"light\" | \"dark\" | \"system\";\n /**\n * Fallback for the `Suspense` boundary wrapped around the children — the\n * stand-in for the view's own `Loading` export, which the real router\n * supplies. Defaults to `null`.\n */\n fallback?: ReactNode;\n /**\n * Renders in place of the children when one throws, mirroring a view's\n * `Error` export. Without it a thrown render (an errored suspense query,\n * say) propagates out of `render()` and fails the test, which is usually\n * what you want.\n */\n errorFallback?: ComponentType<FallbackProps>;\n /**\n * Called when something navigates — a `Link` click, `useNavigate().push`.\n * The navigation is reported, not performed: `<Page>` renders one route and\n * does not re-resolve the tree, so `useLocation()` keeps reporting the\n * pathname it was given.\n */\n onNavigate?: (href: string, action: \"push\" | \"replace\") => void;\n /**\n * The socket `useChannel`, `useChannelInvalidate` and `useQuery({ live })`\n * subscribe through: a `fakeSocket()` the test pushes events and resyncs\n * into. Left out, a fake of the page's own is used, so a component test\n * never opens a WebSocket.\n */\n socket?: FakeSocket;\n}\n\n/** `\"?a=b\"` (or `\"\"`) from any of the shapes `searchParams` accepts. */\nfunction toSearchString(search: PageProps[\"searchParams\"]): string {\n if (!search) return \"\";\n const query =\n typeof search === \"string\"\n ? search.replace(/^\\?/, \"\")\n : new URLSearchParams(\n Object.entries(search).map(([key, value]) => [key, String(value)]),\n ).toString();\n return query ? `?${query}` : \"\";\n}\n\n/**\n * The `:params` a seed key needs supplied. Wildcards (`:rest*`) are excluded —\n * `applyParams` drops those when missing, which is a resolution rather than a\n * failure.\n *\n * Optional params (`:id?`) cannot reach here at all: a key is split at its\n * first `?` to separate the search string, so `\"/lists/:folderId?\"` arrives as\n * the path `/lists/:folderId`. Seed the resolved path for those.\n */\nfunction requiredParamsOf(path: string): string[] {\n return Array.from(path.matchAll(/:([^/]+)/g), ([, name]) => name).filter(\n (name) => !name.endsWith(\"*\"),\n );\n}\n\n/**\n * Fails a `queryData` key whose `:params` the page does not carry, saying so\n * in terms of the key.\n *\n * Without this the two documented runners disagree, and neither is legible.\n * `applyParams` throws `Missing parameter: orgId` under `import.meta.env.DEV`\n * (vitest) — a router-utility stack trace out of `<Page>`'s render, before\n * anything mounts, naming nothing that appears in the test. Under `bun test`\n * that flag is falsy, so it logs and seeds the literal `/orgs/undefined/lists`\n * instead: the seed misses, the query goes to the network, and the assertion\n * runs against a loading state.\n *\n * The case is common because a query's params often come from the call site\n * rather than the route — `useQuery(\"/orgs/:orgId/lists\", { params: { orgId } })`\n * with `orgId` in component state. The cache is keyed by the *resolved* path,\n * so the way out is to seed that path directly.\n */\nfunction resolveSeedPath(\n key: string,\n rawPath: string,\n params: Record<string, string>,\n): string {\n const missing = requiredParamsOf(rawPath).filter(\n (name) => params[name] === undefined,\n );\n if (missing.length > 0) {\n throw new Error(\n `[gemi] <Page> cannot resolve the queryData key \"${key}\": no value for ` +\n `${missing.map((name) => `:${name}`).join(\", \")}. The query cache is ` +\n `keyed by the resolved path, so either add ${missing\n .map((name) => `\\`${name}\\``)\n .join(\", \")} to the page's \\`params\\`, or seed the resolved path ` +\n `(e.g. \"${applyParams(\n rawPath,\n Object.fromEntries(missing.map((name) => [name, \"123\"])),\n )}\") — which is what a query taking its params from component state ` +\n `reads under.`,\n );\n }\n return applyParams(rawPath, params);\n}\n\n/**\n * `queryData` in the shape the query cache seeds from: `{ [path]: { [variant]:\n * data } }`, the same payload `Query.prefetch` puts on a server-rendered page.\n */\nfunction toPrefetchedData(\n queryData: Record<string, unknown>,\n params: Record<string, string>,\n warned: Set<string>,\n) {\n const prefetchedData: Record<string, Record<string, unknown>> = {};\n for (const [key, data] of Object.entries(queryData)) {\n const [rawPath, rawSearch = \"\"] = key.split(\"?\");\n // Once per key per page, not once per render: this runs again on every\n // re-render, and a duplicated warning reads as a second mistake.\n if (rawPath.startsWith(\"/api/\") && !warned.has(key)) {\n warned.add(key);\n console.warn(\n `[gemi] queryData key \"${key}\" starts with /api. useQuery is keyed by ` +\n `the path you pass it — the /api prefix is added when it fetches — ` +\n `so this entry seeds a path no query reads.`,\n );\n }\n const path = resolveSeedPath(key, rawPath, params);\n prefetchedData[path] = {\n ...prefetchedData[path],\n [toVariantKey(rawSearch)]: data,\n };\n }\n return prefetchedData;\n}\n\n/**\n * `{ [locale]: { [dictionary]: { [key]: string } } }` — the payload\n * `Translator` serializes onto the page, which is the only form the client\n * ever sees. `dictionaries` are transposed into it (they are keyed the other\n * way round, by key then locale); `translations` is already in it and lands\n * under `locale`, last, so it wins.\n */\nfunction toClientDictionary(\n dictionaries: PageDictionary[],\n locales: string[],\n locale: string,\n translations: Record<string, Record<string, string>>,\n): Record<string, Record<string, Record<string, string>>> {\n const clientDictionary: Record<\n string,\n Record<string, Record<string, string>>\n > = {};\n for (const supported of locales) {\n clientDictionary[supported] ??= {};\n }\n for (const { name, dictionary } of dictionaries) {\n for (const [key, byLocale] of Object.entries(dictionary ?? {})) {\n for (const [dictLocale, translation] of Object.entries(byLocale ?? {})) {\n clientDictionary[dictLocale] ??= {};\n clientDictionary[dictLocale][name] ??= {};\n clientDictionary[dictLocale][name][key] = translation;\n }\n }\n }\n for (const [name, keys] of Object.entries(translations)) {\n clientDictionary[locale] ??= {};\n clientDictionary[locale][name] = {\n ...clientDictionary[locale][name],\n ...keys,\n };\n }\n return clientDictionary;\n}\n\n/**\n * Mounts a component with the inputs a view normally arrives with — route\n * params, the current locale and its dictionaries, prefetched query data, the\n * signed-in user — so a unit test can assert what it renders rather than only\n * its empty state.\n *\n * ```tsx\n * import { render, screen } from \"@testing-library/react\";\n * import { Page } from \"gemi/testing\";\n *\n * render(\n * <Page\n * pathname=\"/app/:orgId/chat\"\n * params={{ orgId: \"abc\" }}\n * queryData={{ \"/organizations/:orgId/messages\": [{ id: 1, body: \"hi\" }] }}\n * dictionaries={[ChatDictionary]}\n * >\n * <OrgChat />\n * </Page>,\n * );\n *\n * expect(screen.getByText(\"hi\")).toBeDefined();\n * ```\n *\n * It is a plain component, so it composes with any renderer — Testing\n * Library's `render`, `react-test-renderer`, or `renderToString`.\n *\n * Two things it does not do.\n *\n * It does not route: there is no view tree and no route manifest behind it, so\n * a navigation is reported through `onNavigate` rather than resolved. To\n * assert the page *after* one, render a second `<Page>`.\n *\n * And under `renderToString` it renders the server's own no-data branch for an\n * *unseeded* query rather than suspending — deliberately, because suspending\n * there is the streaming server's job: `createRoot` threads the request's\n * `ServerQueryStore` through `ServerQueryContext`, and that store is what runs\n * the route handler. A harness has no request and no handler to run, so there\n * is nothing to suspend on. Seeded queries render their data on the server\n * exactly as they do in the browser; unseeded ones behave as a route with no\n * `Query.prefetch` does, framework warning included.\n */\nexport const Page = (props: PropsWithChildren<PageProps>) => {\n const {\n children,\n pathname: routePath = \"/\",\n params = {},\n searchParams,\n hash = \"\",\n locale = \"en-US\",\n defaultLocale = locale,\n timeZone = \"UTC\",\n dictionaries = [],\n translations = {},\n queryData = {},\n queryConfig,\n user = null,\n breadcrumbs = [],\n domain = null,\n features = {},\n theme,\n fallback = null,\n errorFallback,\n onNavigate,\n socket,\n } = props;\n const [ownSocket] = useState(() => new FakeSocket());\n\n // The caller's list, in the caller's order — a language switcher maps over\n // it, so hoisting the page's own locale to the front would reorder the\n // rendered options. The defaults are appended, only to guarantee presence.\n const supportedLocales = useMemo(\n () =>\n Array.from(\n new Set([...(props.supportedLocales ?? []), defaultLocale, locale]),\n ),\n [props.supportedLocales, defaultLocale, locale],\n );\n const pathname = applyParams(routePath, params) || \"/\";\n // `root` defaults to the host minus its first label, so a tenant subdomain\n // needs only its host; `origin` to https on that host. Either can be given\n // outright when the test is about the other.\n const domainValue = useMemo(() => {\n if (!domain) {\n return null;\n }\n const labels = domain.host.split(\".\");\n return {\n host: domain.host,\n group: domain.group ?? \"\",\n params: domain.params ?? {},\n custom: domain.custom ?? false,\n root:\n domain.root ?? (labels.length > 2 ? labels.slice(1).join(\".\") : domain.host),\n origin: domain.origin ?? `https://${domain.host}`,\n };\n }, [domain]);\n const search = toSearchString(searchParams);\n // The URL's locale segment, which the default locale does not get.\n const urlLocaleSegment = locale === defaultLocale ? null : locale;\n\n const dictionary = useMemo(\n () =>\n toClientDictionary(dictionaries, supportedLocales, locale, translations),\n [dictionaries, supportedLocales, locale, translations],\n );\n\n // Keys that have already drawn a warning, so a re-render does not repeat it.\n const warnedRef = useRef<Set<string>>(new Set());\n const prefetchedData = useMemo(() => {\n const seeded = toPrefetchedData(queryData, params, warnedRef.current);\n // `useUser` reads `/auth/me` like any other query. Seeding it — with `null`\n // for the anonymous default — is what keeps a component test off the\n // network for a hook nothing in the test asked for.\n seeded[\"/auth/me\"] ??= { \"\": user ?? null };\n return seeded;\n }, [queryData, params, user]);\n\n // Keyed by `${view}:${route template}` in the router's cache, which is what\n // `useBreadcrumbs` reads through `useRoute()`; the view names are ours to\n // choose here, and only their order reaches `useBreadcrumbs`.\n const { breadcrumbViews, breadcrumbsCache, breadcrumbsRecord } =\n useMemo(() => {\n const views = breadcrumbs.map((_, index) => `breadcrumb-${index}`);\n const cache = new Map<string, Breadcrumb>(\n breadcrumbs.map((breadcrumb, index) => [\n `${views[index]}:${routePath}`,\n breadcrumb,\n ]),\n );\n return {\n breadcrumbViews: views,\n breadcrumbsCache: cache,\n breadcrumbsRecord: Object.fromEntries(cache),\n };\n }, [breadcrumbs, routePath]);\n\n const [isNavigatingSubject] = useState(() => new Subject<boolean>(false));\n const [progressManager] = useState(\n () => new ProgressManager(isNavigatingSubject),\n );\n const [history] = useState(() =>\n createMemoryHistory({ initialEntries: [`${pathname}${search}${hash}`] }),\n );\n\n const routeState: RouteState & PageData = useMemo(\n () => ({\n views: [],\n params,\n search,\n state: {},\n pathname,\n hash,\n action: null,\n routePath,\n locale: urlLocaleSegment,\n data: {},\n i18n: {\n currentLocale: locale,\n dictionary,\n supportedLocales,\n defaultLocale,\n timeZone,\n },\n prefetchedData,\n breadcrumbs: breadcrumbsRecord,\n features: features as Record<string, boolean>,\n appId: \"test\",\n }),\n [\n params,\n search,\n pathname,\n hash,\n routePath,\n urlLocaleSegment,\n locale,\n dictionary,\n supportedLocales,\n defaultLocale,\n timeZone,\n prefetchedData,\n breadcrumbsRecord,\n features,\n ],\n );\n\n const [routerSubject] = useState(() => new Subject<RouteState>(routeState));\n\n const onNavigateRef = useRef(onNavigate);\n onNavigateRef.current = onNavigate;\n // Subscribed during render, not in an effect, because React flushes child\n // effects before parent ones — and mount-time navigation is a real pattern:\n // `<Redirect>` pushes from its own mount effect, as does any auth guard. A\n // listener registered in `<Page>`'s effect is not there yet when those fire,\n // so `onNavigate` would silently miss exactly the redirects a test most\n // wants to assert. Ref-guarded, so React's double-invoke registers one.\n //\n // Nothing unsubscribes: this history is created per `<Page>` and reachable\n // from nowhere else, so it is collected with the page it belongs to.\n const listeningRef = useRef(false);\n if (!listeningRef.current) {\n listeningRef.current = true;\n history.listen(({ location, action }) => {\n const href = `${location.pathname}${location.search}${location.hash}`;\n onNavigateRef.current?.(\n href,\n action === Action.Replace ? \"replace\" : \"push\",\n );\n });\n }\n\n const serverData: ServerDataContextValue = useMemo(\n () => ({\n routeManifest: {},\n pageData: {},\n breadcrumbs: breadcrumbsRecord,\n prefetchedData,\n // As the server sends it: `pathname` is the route template and\n // `currentPath` the URL, locale segment included.\n router: {\n pathname: routePath,\n params,\n currentPath: `${urlLocaleSegment ? `/${urlLocaleSegment}` : \"\"}${pathname}`,\n is404: false,\n searchParams: search,\n urlLocaleSegment,\n domain: domainValue,\n },\n i18n: {\n dictionary,\n currentLocale: locale,\n supportedLocales,\n defaultLocale,\n timeZone,\n },\n componentTree: [],\n auth: { user: user as User },\n features: features as Record<string, boolean>,\n __csrf: \"test-csrf-token\",\n cssManifest: {},\n modulePreloadManifest: {},\n meta: {},\n appId: \"test\",\n }),\n [\n breadcrumbsRecord,\n prefetchedData,\n pathname,\n params,\n routePath,\n search,\n urlLocaleSegment,\n dictionary,\n locale,\n supportedLocales,\n defaultLocale,\n timeZone,\n user,\n features,\n ],\n );\n\n // Everything the router hooks read, inert: nothing here fetches, preloads or\n // resolves a route, but every hook finds the shape it expects rather than an\n // empty context to crash on.\n const [viewEntriesSubject] = useState(() => new Subject<string[]>([]));\n const routerContext = useMemo(\n () => ({\n viewEntriesSubject,\n history,\n updatePageData: () => {},\n getPageData: () => ({}),\n getScrollPosition: () => 0,\n getViewPathsFromPathname: () => breadcrumbViews,\n getRoutePathnameFromHref: (href: string) => href,\n isNavigatingSubject,\n setNavigationAbortController: () => {},\n progressManager,\n fetchRouteCSS: async () => {},\n preloadRouteModules: () => {},\n prefetchRoute: async () => {},\n takePrefetched: () => null,\n clearPrefetchCache: () => {},\n breadcrumbsCache,\n routerSubject,\n urlLocaleSegment,\n }),\n [\n viewEntriesSubject,\n history,\n breadcrumbViews,\n isNavigatingSubject,\n progressManager,\n breadcrumbsCache,\n routerSubject,\n urlLocaleSegment,\n ],\n );\n\n return (\n <ThemeProvider theme={theme}>\n <ServerDataContext.Provider value={serverData}>\n <I18nProvider>\n <QueryManagerProvider queryConfig={queryConfig}>\n <ClientRouterContext.Provider value={routerContext}>\n <RouteTransitionProvider\n isPending={false}\n isFetching={false}\n transitionPath={[\"\", pathname]}\n >\n <RouteStateProvider state={routeState}>\n <RealtimeContext.Provider value={socket ?? ownSocket}>\n <Boundary\n errorFallback={errorFallback}\n fallback={fallback}\n resetKey={pathname}\n >\n {children}\n </Boundary>\n </RealtimeContext.Provider>\n </RouteStateProvider>\n </RouteTransitionProvider>\n </ClientRouterContext.Provider>\n </QueryManagerProvider>\n </I18nProvider>\n </ServerDataContext.Provider>\n </ThemeProvider>\n );\n};\n\n/**\n * The `Suspense` boundary every view renders inside, and — when the test\n * supplies a fallback for it — the error boundary too.\n *\n * `onReset={clearErrors}` is the part that has to be here rather than inline\n * above: it needs `QueryManagerContext`, and it is what makes a view's real\n * `Error` export testable. A fallback whose \"Try again\" calls\n * `resetErrorBoundary()` re-renders the child, and `useQuery` reads the\n * failure still stored on the `QueryResource` and throws it straight back —\n * so without this the fallback never goes away and the retry path that works\n * in the app cannot be exercised. `ClientRouter`'s own boundary wires exactly\n * this pair.\n */\nconst Boundary = (\n props: PropsWithChildren<{\n errorFallback?: ComponentType<FallbackProps>;\n fallback: ReactNode;\n resetKey: string;\n }>,\n) => {\n const { errorFallback: ErrorFallback, fallback, resetKey, children } = props;\n const { clearErrors } = useContext(QueryManagerContext);\n const content = <Suspense fallback={fallback}>{children}</Suspense>;\n\n if (!ErrorFallback) {\n return content;\n }\n\n return (\n <ErrorBoundary\n FallbackComponent={ErrorFallback}\n resetKeys={[resetKey]}\n onReset={clearErrors}\n >\n {content}\n </ErrorBoundary>\n );\n};\n","/**\n * The browser side of islands, shared by the Vite plugin (which builds it), the\n * servers (which point the loader at it) and the tests.\n *\n * No imports: the Vite plugin is built on its own and the servers load it at\n * boot, so this file stays plain strings.\n */\n\n/**\n * The module that hydrates islands: React, `react-dom/client` and the small\n * `h(marker, Component)` below. A virtual module of gemi's Vite plugin that\n * every island entry imports, so the islands on a page share one copy of\n * React, in one chunk.\n */\nexport const ISLAND_RUNTIME_ID = \"virtual:gemi-island-runtime\";\n\n/** What `resolveId` turns `ISLAND_RUNTIME_ID` into (Vite's virtual-module convention). */\nexport const RESOLVED_ISLAND_RUNTIME_ID = `\\0${ISLAND_RUNTIME_ID}`;\n\n/**\n * The query that turns a module into its island entry: `Counter.tsx?gemi-island`\n * is a module of the plugin's that re-exports `Counter.tsx` as `m` next to the\n * runtime's `h`. It is what a static page imports for an island, and so it\n * is what the client manifest lists, keyed `app/…/Counter.tsx?gemi-island`,\n * with React and `react-dom/client` among its imports.\n */\nexport const ISLAND_ENTRY_QUERY = \"?gemi-island\";\n\n/** The island entry module for `file` (an absolute path or a root-relative URL). */\nexport function islandEntrySource(file: string) {\n return `import * as m from ${JSON.stringify(file)};\nexport { m };\nexport { h } from ${JSON.stringify(ISLAND_RUNTIME_ID)};\n`;\n}\n\n/**\n * `h(marker, Component)`: hydrates one `<gemi-island>` marker with the island's\n * component and the props the server serialised into `data-props`.\n *\n * The island's static children were rendered on the server into a\n * `<gemi-slot>` (the first one that belongs to this marker, not to an island\n * nested in it). They are handed back to the component as that same element\n * with the server's HTML, so hydration matches and React leaves them alone.\n *\n * `data-uid` is the `identifierPrefix` the server rendered the island with, so\n * `useId` agrees on both sides and two islands never share an id.\n *\n * When the page carries `#gemi-island-i18n` (its islands read the page's\n * locale or dictionaries, #1095), the dictionaries in it are seeded into the\n * dictionary registry through `__GEMI_DICT__` and the island's root gets the\n * locale and zone in `IslandI18nContext` (found on `globalThis`, where\n * `gemi/client` puts it), so `useDictionary` resolves synchronously, with the\n * strings the server rendered, and fetches nothing. An island that does not\n * import `gemi/client` has no such context to read, and is left as it was.\n *\n * The island's root reads queries through the cache the page's islands\n * share (found on `globalThis` under `gemi.islandQueries`, where `gemi/client`\n * puts it, #1155). When the page carries `#gemi-island-queries` (its islands\n * read queries the request prefetched), that `{ path: { variantKey: data } }`\n * payload seeds the cache first, so `useQuery` hydrates with the server's\n * data and does not refetch it.\n *\n * Written as a function body with `createElement` and `hydrateRoot` free, so a\n * test can run it against real React without a bundler.\n */\nexport const ISLAND_HYDRATE_SOURCE = `function h(marker, Component) {\n if (typeof Component !== \"function\" && (typeof Component !== \"object\" || Component === null)) {\n throw new Error(\"gemi: island module has no component export for \" + marker.outerHTML.slice(0, 80));\n }\n const json = marker.getAttribute(\"data-props\");\n const props = json ? JSON.parse(json) : {};\n let slot = null;\n for (const candidate of marker.querySelectorAll(\"gemi-slot\")) {\n if (candidate.closest(\"gemi-island\") === marker) {\n slot = candidate;\n break;\n }\n }\n const children = slot\n ? [createElement(\"gemi-slot\", {\n style: { display: \"contents\" },\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: { __html: slot.innerHTML },\n })]\n : [];\n let element = createElement(Component, props, ...children);\n const i18n = document.getElementById(\"gemi-island-i18n\");\n const context = globalThis[Symbol.for(\"gemi.islandI18n\")];\n if (i18n && context) {\n const payload = (i18n.p = i18n.p || JSON.parse(i18n.textContent));\n const dictionaries = (self.__GEMI_DICT__ = self.__GEMI_DICT__ || []);\n for (const entry of payload.dictionaries || []) dictionaries.push(entry);\n element = createElement(context.Provider, {\n value: { currentLocale: payload.currentLocale, defaultLocale: payload.defaultLocale, timeZone: payload.timeZone },\n }, element);\n }\n const cache = globalThis[Symbol.for(\"gemi.islandQueries\")];\n if (cache) {\n const queries = document.getElementById(\"gemi-island-queries\");\n if (queries) cache.seed((queries.p = queries.p || JSON.parse(queries.textContent)));\n element = createElement(cache.Provider, null, element);\n }\n return hydrateRoot(marker, element, {\n identifierPrefix: marker.getAttribute(\"data-uid\") || undefined,\n });\n}`;\n\n/** The runtime module's source, as the plugin serves and builds it. */\nexport const ISLAND_RUNTIME_SOURCE = `import { createElement } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nexport ${ISLAND_HYDRATE_SOURCE}\n`;\n\n/**\n * The island loader, inlined into a static document that uses islands.\n *\n * Kept byte-for-byte constant (the per-page island table travels in a\n * separate `<script type=\"application/json\">`, which a Content Security Policy\n * does not treat as script), so a strict policy can allow it by hash:\n * `script-src 'sha256-…'` with `ISLAND_LOADER_CSP_HASH`. Everything it loads\n * is a plain `import()` of a same-origin (or asset-base) file.\n *\n * The table is `{ i: [{ s: entry URL, e: export, l: load }] }` and each\n * marker's `data-island` indexes `i`. Per marker, on its schedule: import the\n * island's entry (the module as `m`, the runtime's `h`), then\n * `h(marker, m[export])`, which calls `hydrateRoot`. A failure is logged and\n * leaves the server-rendered markup in place.\n */\nexport const ISLAND_LOADER_SOURCE =\n 'const d=document,c=JSON.parse(d.getElementById(\"gemi-islands\").textContent),' +\n \"w=f=>(window.requestIdleCallback||setTimeout)(f),\" +\n \"m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};\" +\n 'for(const e of d.querySelectorAll(\"gemi-island\")){const o=c.i[e.dataset.island];if(!o)continue;' +\n 'if(o.l==\"eager\")m(e,o);else if(o.l==\"idle\"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));' +\n \"else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}\";\n","// Generated by `bun scripts/build-static-navigation.ts` from\n// `internal/staticNavigation/runtime.js`. Do not edit; edit the source and regenerate.\n// No imports: `gemi/testing` (a browser bundle) and `gemi stats` read it too.\n\n/** The sha-256 of the source this was built from, so a test can tell it is stale. */\nexport const STATIC_NAVIGATION_SOURCE_HASH = \"7150f8f2959c2cd5f5b6f784452c2aa520d7d06cbe52402b2de7bc85317ac3d6\";\n\n/**\n * The navigation runtime (with the island loader) a static view with\n * `.static({ navigation })` inlines. Byte-for-byte constant.\n */\nexport const STATIC_NAVIGATION_SOURCE =\n \"var r=document,i=window,a=history;i.__gemi_nav?.d();var C=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:C.signal,...s}),q=i.__gemi_nav={d:()=>C.abort()},y=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},L=(t)=>{let e=t.getElementById(\\\"gemi-islands\\\");return e?JSON.parse(e.textContent):{i:[]}},D=(t,e)=>{for(let n of t.querySelectorAll(\\\"gemi-island\\\")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l==\\\"eager\\\")y(n,s);else if(s.l==\\\"idle\\\"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>y(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),y(n,s)});for(let m of n.children)l.observe(m)}}},R='meta[name=\\\"gemi-static\\\"]',A=\\\"style:not([data-gemi-fonts])\\\",T=A+\\\",link[rel=stylesheet]\\\",K=`head>${A},body>${A},link[rel=stylesheet]`,I='meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type=\\\"application/ld+json\\\"]',w=(t)=>t.querySelector(R)?.content,O=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split(\\\"#\\\")[0],N=O(r),p=r.createElement(\\\"div\\\");p.setAttribute(\\\"aria-live\\\",\\\"polite\\\");p.style.cssText=\\\"position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap\\\";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent(\\\"gemi:page-load\\\",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:\\\"text/html\\\",\\\"x-gemi-navigate\\\":\\\"1\\\"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\\\/html/.test(s.headers.get(\\\"content-type\\\"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.(\\\"a[href]\\\"),n=e?.getAttribute(\\\"target\\\");if(!e||n&&n!=\\\"_self\\\"||e.hasAttribute(\\\"download\\\")||/(^|\\\\s)external(\\\\s|$)/i.test(e.getAttribute(\\\"rel\\\"))||e.closest(\\\"[data-gemi-reload]\\\"))return;let s=new URL(e.getAttribute(\\\"href\\\"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes(\\\"#\\\")&&c(s)==c(location)))return s},v={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},\\\"\\\"),P=c(location),b=0,Y=(t)=>{if(!t.hasAttribute(\\\"tabindex\\\"))t.setAttribute(\\\"tabindex\\\",\\\"-1\\\"),t.addEventListener(\\\"blur\\\",()=>t.removeAttribute(\\\"tabindex\\\"),{once:!0});t.focus({preventScroll:!0})},j=(t)=>{let e=r.body,n=t.body,s=L(t),l=r.documentElement;r.title=t.title;for(let o of[\\\"lang\\\",\\\"dir\\\"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll(\\\"link[rel=modulepreload]\\\")].map((o)=>o.getAttribute(\\\"href\\\")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll(\\\"link[rel=modulepreload]\\\")].filter((o)=>!m.has(o.getAttribute(\\\"href\\\"))));let d=new Map([...e.querySelectorAll(\\\"[data-gemi-persist]\\\")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll(\\\"[data-gemi-persist]\\\")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll(\\\"gemi-island\\\")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),D(e,s)},H=async(t,e)=>{let n=++b,s=!e&&v[a.state?.g];a.scrollRestoration=\\\"manual\\\";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,\\\"text/html\\\");if(w(d)==null||w(d)!=w(r)||O(d)!=N)throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},\\\"\\\",o.href)}P=c(location),j(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:\\\"instant\\\"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:\\\"instant\\\"});if(e)Y(g||r.querySelector(\\\"h1\\\")||r.querySelector(\\\"main\\\")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,\\\"click\\\",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent(\\\"gemi:before-navigate\\\",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),v[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,\\\"popstate\\\",()=>{if(b++,c(location)==P){let t=v[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:\\\"instant\\\"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,\\\"hashchange\\\",E);h(i,\\\"scroll\\\",()=>a.state?.g&&(v[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(R)?.dataset.prefetch==\\\"none\\\"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,\\\"pointerover\\\",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,\\\"pointerout\\\",()=>clearTimeout(S));h(r,\\\"focusin\\\",x);h(r,\\\"touchstart\\\",x,{passive:!0});E();D(r,L(r));_(!0);\";\n","import { createElement } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { ISLAND_HYDRATE_SOURCE } from \"../internal/islandRuntime\";\nimport { STATIC_NAVIGATION_SOURCE } from \"../internal/staticNavigationRuntime\";\n\n/**\n * One page `renderStaticDocument` serves to the navigation runtime: its HTML, or\n * a response of another kind to see the runtime fall back to a full load.\n */\nexport interface StaticTestPage {\n html?: string;\n /** Default 200. */\n status?: number;\n /** Default `text/html; charset=utf-8`. */\n contentType?: string;\n /** The URL the response ends at, as after a redirect. Default: the one asked for. */\n url?: string;\n}\n\nexport interface StaticDocumentOptions {\n /** The document's URL, resolved against the test window's origin. Default `/`. */\n url?: string;\n /**\n * What the runtime's `fetch` gets, by path (`/about`, `/about?x=1`) or full\n * URL: HTML, a `StaticTestPage`, or a function for anything else. A URL\n * not listed is a 404.\n */\n pages?:\n | Record<string, string | StaticTestPage>\n | ((url: URL) => string | StaticTestPage | Promise<string | StaticTestPage>);\n /**\n * The island modules, by the entry URL the page's island table names (`s`):\n * each a module whose exports include the islands' components. Hydrated\n * with React, as `<module>?gemi-island` would.\n */\n islands?: Record<string, Record<string, unknown>>;\n /**\n * Run the page's document script (`.static({ script })`) once, before the\n * runtime starts, as the browser would. Off by default. Scripts of pages\n * swapped in later never run, as in the browser.\n */\n documentScript?: boolean;\n}\n\n/** How a navigation ended. */\nexport type StaticNavigationResult =\n /** The runtime swapped the fetched page in. */\n | { kind: \"swap\"; url: string }\n /** The runtime gave up on a swap and asked for a full page load of `url`. */\n | { kind: \"full-load\"; url: string }\n /** The runtime left the click alone: the browser would follow the link itself. */\n | { kind: \"native\" };\n\nexport interface StaticDocumentHandle {\n /**\n * Clicks the page's first `<a>` whose `href` attribute is `href` and waits\n * for the outcome. Throws when there is no such link.\n */\n navigate(href: string, init?: MouseEventInit): Promise<StaticNavigationResult>;\n /** `history.back()`, and waits for the runtime to show that entry. */\n back(): Promise<StaticNavigationResult>;\n /** Every URL the runtime fetched, prefetches included, in order. */\n requests: string[];\n /** Every full page load the runtime asked for. */\n fullLoads: string[];\n /** Stops the runtime and restores what the helper stubbed. */\n dispose(): void;\n}\n\nconst hydrate = new Function(\n \"createElement\",\n \"hydrateRoot\",\n `${ISLAND_HYDRATE_SOURCE};return h;`,\n)(createElement, hydrateRoot) as (marker: Element, component: unknown) => unknown;\n\n/**\n * Puts a static document (`.static({ navigation })`) into the test's DOM and\n * starts its navigation runtime against stubbed pages, so a test can check that\n * a site's links are followed client-side, and what the next page looks like.\n * Needs a DOM (`// @vitest-environment jsdom` or `happy-dom`).\n *\n * ```ts\n * const html = await (await render(\"/\")).text(); // the page, from your app\n * const page = renderStaticDocument(html, { pages: { \"/about\": aboutHtml } });\n * expect(await page.navigate(\"/about\")).toEqual({ kind: \"swap\", url: \"http://localhost:3000/about\" });\n * expect(document.querySelector(\"h1\")!.textContent).toBe(\"About\");\n * page.dispose();\n * ```\n *\n * The document's own scripts do not run (the helper runs the runtime itself,\n * and the document script with `documentScript: true`), and a link the runtime leaves alone is not followed. Islands hydrate\n * asynchronously, as in a browser: wrap what follows in `act`, or wait for it.\n */\nexport function renderStaticDocument(\n html: string,\n options: StaticDocumentOptions = {},\n): StaticDocumentHandle {\n const requests: string[] = [];\n const fullLoads: string[] = [];\n let settle: ((result: StaticNavigationResult) => void) | undefined;\n const outcome = () =>\n new Promise<StaticNavigationResult>((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(\"the navigation did not finish in 5 s\")), 5000);\n settle = (result) => {\n clearTimeout(timer);\n settle = undefined;\n resolve(result);\n };\n });\n\n history.replaceState(null, \"\", options.url ?? \"/\");\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n const documentScript = options.documentScript\n ? parsed.querySelector(\"head > script[data-gemi-script]\")?.textContent\n : undefined;\n for (const script of Array.from(parsed.querySelectorAll(\"script\"))) {\n if (!/json/.test(script.type)) script.remove();\n }\n // Removed, then appended: happy-dom refuses a second root element, which\n // `replaceChild` (insert, then remove) would make for a moment (#1102).\n const root = document.importNode(parsed.documentElement, true);\n document.removeChild(document.documentElement);\n document.appendChild(root);\n\n const fullLoad = (url: string) => {\n fullLoads.push(url);\n settle?.({ kind: \"full-load\", url });\n };\n const location = {\n get href() {\n return window.location.href;\n },\n get origin() {\n return window.location.origin;\n },\n assign: (url: string) => fullLoad(new URL(url, window.location.href).href),\n reload: () => fullLoad(window.location.href),\n };\n\n const pages = options.pages ?? {};\n const fetch = async (input: string) => {\n const url = new URL(input, window.location.href);\n requests.push(url.href);\n const page =\n typeof pages === \"function\"\n ? await pages(url)\n : (pages[url.href] ?? pages[url.pathname + url.search]);\n const spec: StaticTestPage =\n page === undefined\n ? { status: 404, html: \"not found\", contentType: \"text/plain\" }\n : typeof page === \"string\"\n ? { html: page }\n : page;\n const response = new Response(spec.html ?? \"\", {\n status: spec.status ?? 200,\n headers: { \"content-type\": spec.contentType ?? \"text/html; charset=utf-8\" },\n });\n Object.defineProperty(response, \"url\", { value: new URL(spec.url ?? url.href, url).href });\n return response;\n };\n\n const importIsland = async (src: string) => {\n const module = options.islands?.[src];\n if (!module) throw new Error(`renderStaticDocument: no island module for ${src} in options.islands`);\n return { m: module, h: hydrate };\n };\n\n // The runtime announces a click it takes with `gemi:before-navigate`; one\n // it does not take (or one a listener cancelled) is the browser's, which\n // jsdom would try (and fail) to follow, so it is stopped here, on `window`,\n // after every listener on the way.\n let announced: Event | undefined;\n const onBeforeNavigate = (event: Event) => {\n announced = event;\n };\n document.addEventListener(\"gemi:before-navigate\", onBeforeNavigate);\n const onClick = (event: Event) => {\n const taken = announced !== undefined && !announced.defaultPrevented;\n announced = undefined;\n if (taken || !(event.target as Element).closest?.(\"a[href]\")) return;\n event.preventDefault();\n settle?.({ kind: \"native\" });\n };\n window.addEventListener(\"click\", onClick);\n const onPageLoad = (event: Event) => {\n const detail = (event as CustomEvent<{ url: string; initial: boolean }>).detail;\n if (!detail.initial) settle?.({ kind: \"swap\", url: detail.url });\n };\n document.addEventListener(\"gemi:page-load\", onPageLoad);\n\n // Not implemented by jsdom.\n const scrollTo = window.scrollTo;\n window.scrollTo = () => {};\n const scrollIntoView = Element.prototype.scrollIntoView;\n Element.prototype.scrollIntoView = function () {};\n\n // A head module script runs before the runtime at the end of the body.\n if (documentScript) new Function(documentScript)();\n\n const source = STATIC_NAVIGATION_SOURCE.replace(\"import(\", \"__import(\");\n new Function(\"__import\", \"location\", \"fetch\", source)(importIsland, location, fetch);\n\n return {\n requests,\n fullLoads,\n async navigate(href, init) {\n const link = Array.from(document.querySelectorAll(\"a[href]\")).find(\n (a) => a.getAttribute(\"href\") === href,\n );\n if (!link) throw new Error(`renderStaticDocument: no <a href=\"${href}\"> on the page`);\n const done = outcome();\n link.dispatchEvent(new MouseEvent(\"click\", { bubbles: true, cancelable: true, ...init }));\n return await done;\n },\n async back() {\n const done = outcome();\n history.back();\n return await done;\n },\n dispose() {\n (window as unknown as { __gemi_nav?: { d: () => void } }).__gemi_nav?.d();\n window.removeEventListener(\"click\", onClick);\n document.removeEventListener(\"gemi:before-navigate\", onBeforeNavigate);\n document.removeEventListener(\"gemi:page-load\", onPageLoad);\n window.scrollTo = scrollTo;\n Element.prototype.scrollIntoView = scrollIntoView;\n },\n };\n}\n"],"mappings":";;;;;;;AAoBA,IAAM,kBAAkB;AACxB,IAAM,gBAAgB;AACtB,IAAM,cAAc;;AAmCpB,IAAa,sBAAb,cAAyC,MAAM;CAC7C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAYA,SAAgB,aAAa,SAA2B;CACtD,IAAI,OAAO,YAAY,YAAY,QAAQ,WAAW,GACpD,MAAM,IAAI,oBAAoB,+CAA+C;CAE/E,IAAI,QAAQ,SAAA,KACV,MAAM,IAAI,oBACR,wBAAwB,QAAQ,MAAM,GAAG,EAAE,EAAE,kCAC/C;CAEF,MAAM,WAAW,QAAQ,MAAM,GAAG;CAClC,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,WAAW,UAAU;EAC9B,IAAI,cAAc,KAAK,OAAO,GAAG;GAC/B,MAAM,OAAO,QAAQ,MAAM,CAAC;GAC5B,IAAI,KAAK,IAAI,IAAI,GACf,MAAM,IAAI,oBACR,wBAAwB,QAAQ,qBAAqB,KAAK,SAC5D;GAEF,KAAK,IAAI,IAAI;GACb;EACF;EACA,IAAI,QAAQ,WAAW,IAAI,GACzB,MA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I,CAAC;CACjE;CACA,SAAS,iBAAiB,kBAAkB,UAAU;CAGtD,MAAM,WAAW,OAAO;CACxB,OAAO,iBAAiB,CAAC;CACzB,MAAM,iBAAiB,QAAQ,UAAU;CACzC,QAAQ,UAAU,iBAAiB,WAAY,CAAC;CAGhD,IAAI,gBAAgB,IAAI,SAAS,cAAc,CAAC,CAAC;CAEjD,MAAM,SAAS,yBAAyB,QAAQ,WAAW,WAAW;CACtE,IAAI,SAAS,YAAY,YAAY,SAAS,MAAM,CAAC,CAAC,cAAc,UAAU,KAAK;CAEnF,OAAO;EACL;EACA;EACA,MAAM,SAAS,MAAM,MAAM;GACzB,MAAM,OAAO,MAAM,KAAK,SAAS,iBAAiB,SAAS,CAAC,CAAC,CAAC,MAC3D,MAAM,EAAE,aAAa,MAAM,MAAM,IACpC;GACA,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,qCAAqC,KAAK,eAAe;GACpF,MAAM,OAAO,QAAQ;GACrB,KAAK,cAAc,IAAI,WAAW,SAAS;IAAE,SAAS;IAAM,YAAY;IAAM,GAAG;GAAK,CAAC,CAAC;GACxF,OAAO,MAAM;EACf;EACA,MAAM,OAAO;GACX,MAAM,OAAO,QAAQ;GACrB,QAAQ,KAAK;GACb,OAAO,MAAM;EACf;EACA,UAAU;GACR,OAA0D,YAAY,EAAE;GACxE,OAAO,oBAAoB,SAAS,OAAO;GAC3C,SAAS,oBAAoB,wBAAwB,gBAAgB;GACrE,SAAS,oBAAoB,kBAAkB,UAAU;GACzD,OAAO,WAAW;GAClB,QAAQ,UAAU,iBAAiB;EACrC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../node_modules/.bun/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/esm/extends.js","../../../../node_modules/.bun/history@5.3.0/node_modules/history/index.js","../../services/broadcast/channels.ts","../../client/realtime/FakeSocket.ts","../../testing/Page.tsx","../../internal/islandRuntime.ts","../../internal/staticNavigationRuntime.ts","../../testing/staticDocument.ts"],"sourcesContent":["function _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\nexport { _extends as default };","import _extends from '@babel/runtime/helpers/esm/extends';\n\n/**\r\n * Actions represent the type of change to a location value.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action\r\n */\nvar Action;\n\n(function (Action) {\n /**\r\n * A POP indicates a change to an arbitrary index in the history stack, such\r\n * as a back or forward navigation. It does not describe the direction of the\r\n * navigation, only that the current index changed.\r\n *\r\n * Note: This is the default action for newly created history objects.\r\n */\n Action[\"Pop\"] = \"POP\";\n /**\r\n * A PUSH indicates a new entry being added to the history stack, such as when\r\n * a link is clicked and a new page loads. When this happens, all subsequent\r\n * entries in the stack are lost.\r\n */\n\n Action[\"Push\"] = \"PUSH\";\n /**\r\n * A REPLACE indicates the entry at the current index in the history stack\r\n * being replaced by a new one.\r\n */\n\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\n\nvar readOnly = process.env.NODE_ENV !== \"production\" ? function (obj) {\n return Object.freeze(obj);\n} : function (obj) {\n return obj;\n};\n\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== 'undefined') console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message); // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nvar BeforeUnloadEventType = 'beforeunload';\nvar HashChangeEventType = 'hashchange';\nvar PopStateEventType = 'popstate';\n/**\r\n * Browser history stores the location in regular URLs. This is the standard for\r\n * most web apps, but it requires some configuration on the server to ensure you\r\n * serve the same app at multiple URLs.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\r\n */\n\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$window = _options.window,\n window = _options$window === void 0 ? document.defaultView : _options$window;\n var globalHistory = window.history;\n\n function getIndexAndLocation() {\n var _window$location = window.location,\n pathname = _window$location.pathname,\n search = _window$location.search,\n hash = _window$location.hash;\n var state = globalHistory.state || {};\n return [state.idx, readOnly({\n pathname: pathname,\n search: search,\n hash: hash,\n state: state.usr || null,\n key: state.key || 'default'\n })];\n }\n\n var blockedPopTx = null;\n\n function handlePop() {\n if (blockedPopTx) {\n blockers.call(blockedPopTx);\n blockedPopTx = null;\n } else {\n var nextAction = Action.Pop;\n\n var _getIndexAndLocation = getIndexAndLocation(),\n nextIndex = _getIndexAndLocation[0],\n nextLocation = _getIndexAndLocation[1];\n\n if (blockers.length) {\n if (nextIndex != null) {\n var delta = index - nextIndex;\n\n if (delta) {\n // Revert the POP\n blockedPopTx = {\n action: nextAction,\n location: nextLocation,\n retry: function retry() {\n go(delta * -1);\n }\n };\n go(delta);\n }\n } else {\n // Trying to POP to a location with no index. We did not create\n // this location, so we can't effectively block the navigation.\n process.env.NODE_ENV !== \"production\" ? warning(false, // TODO: Write up a doc that explains our blocking strategy in\n // detail and link to it here so people can understand better what\n // is going on and how to avoid it.\n \"You are trying to block a POP navigation to a location that was not \" + \"created by the history library. The block will fail silently in \" + \"production, but in general you should do all navigation with the \" + \"history library (instead of using window.history.pushState directly) \" + \"to avoid this situation.\") : void 0;\n }\n } else {\n applyTx(nextAction);\n }\n }\n }\n\n window.addEventListener(PopStateEventType, handlePop);\n var action = Action.Pop;\n\n var _getIndexAndLocation2 = getIndexAndLocation(),\n index = _getIndexAndLocation2[0],\n location = _getIndexAndLocation2[1];\n\n var listeners = createEvents();\n var blockers = createEvents();\n\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), '');\n }\n\n function createHref(to) {\n return typeof to === 'string' ? to : createPath(to);\n } // state defaults to `null` because `window.history.state` does\n\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n hash: '',\n search: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function getHistoryStateAndUrl(nextLocation, index) {\n return [{\n usr: nextLocation.state,\n key: nextLocation.key,\n idx: index\n }, createHref(nextLocation)];\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction) {\n action = nextAction;\n\n var _getIndexAndLocation3 = getIndexAndLocation();\n\n index = _getIndexAndLocation3[0];\n location = _getIndexAndLocation3[1];\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),\n historyState = _getHistoryStateAndUr[0],\n url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading\n // try...catch because iOS limits us to 100 pushState calls :/\n\n\n try {\n globalHistory.pushState(historyState, '', url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n applyTx(nextAction);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),\n historyState = _getHistoryStateAndUr2[0],\n url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading\n\n\n globalHistory.replaceState(historyState, '', url);\n applyTx(nextAction);\n }\n }\n\n function go(delta) {\n globalHistory.go(delta);\n }\n\n var history = {\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n var unblock = blockers.push(blocker);\n\n if (blockers.length === 1) {\n window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n\n return function () {\n unblock(); // Remove the beforeunload listener so the document may\n // still be salvageable in the pagehide event.\n // See https://html.spec.whatwg.org/#unloading-documents\n\n if (!blockers.length) {\n window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n };\n }\n };\n return history;\n}\n/**\r\n * Hash history stores the location in window.location.hash. This makes it ideal\r\n * for situations where you don't want to send the location to the server for\r\n * some reason, either because you do cannot configure it or the URL space is\r\n * reserved for something else.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\r\n */\n\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options2 = options,\n _options2$window = _options2.window,\n window = _options2$window === void 0 ? document.defaultView : _options2$window;\n var globalHistory = window.history;\n\n function getIndexAndLocation() {\n var _parsePath = parsePath(window.location.hash.substr(1)),\n _parsePath$pathname = _parsePath.pathname,\n pathname = _parsePath$pathname === void 0 ? '/' : _parsePath$pathname,\n _parsePath$search = _parsePath.search,\n search = _parsePath$search === void 0 ? '' : _parsePath$search,\n _parsePath$hash = _parsePath.hash,\n hash = _parsePath$hash === void 0 ? '' : _parsePath$hash;\n\n var state = globalHistory.state || {};\n return [state.idx, readOnly({\n pathname: pathname,\n search: search,\n hash: hash,\n state: state.usr || null,\n key: state.key || 'default'\n })];\n }\n\n var blockedPopTx = null;\n\n function handlePop() {\n if (blockedPopTx) {\n blockers.call(blockedPopTx);\n blockedPopTx = null;\n } else {\n var nextAction = Action.Pop;\n\n var _getIndexAndLocation4 = getIndexAndLocation(),\n nextIndex = _getIndexAndLocation4[0],\n nextLocation = _getIndexAndLocation4[1];\n\n if (blockers.length) {\n if (nextIndex != null) {\n var delta = index - nextIndex;\n\n if (delta) {\n // Revert the POP\n blockedPopTx = {\n action: nextAction,\n location: nextLocation,\n retry: function retry() {\n go(delta * -1);\n }\n };\n go(delta);\n }\n } else {\n // Trying to POP to a location with no index. We did not create\n // this location, so we can't effectively block the navigation.\n process.env.NODE_ENV !== \"production\" ? warning(false, // TODO: Write up a doc that explains our blocking strategy in\n // detail and link to it here so people can understand better\n // what is going on and how to avoid it.\n \"You are trying to block a POP navigation to a location that was not \" + \"created by the history library. The block will fail silently in \" + \"production, but in general you should do all navigation with the \" + \"history library (instead of using window.history.pushState directly) \" + \"to avoid this situation.\") : void 0;\n }\n } else {\n applyTx(nextAction);\n }\n }\n }\n\n window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge\n // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event\n\n window.addEventListener(HashChangeEventType, function () {\n var _getIndexAndLocation5 = getIndexAndLocation(),\n nextLocation = _getIndexAndLocation5[1]; // Ignore extraneous hashchange events.\n\n\n if (createPath(nextLocation) !== createPath(location)) {\n handlePop();\n }\n });\n var action = Action.Pop;\n\n var _getIndexAndLocation6 = getIndexAndLocation(),\n index = _getIndexAndLocation6[0],\n location = _getIndexAndLocation6[1];\n\n var listeners = createEvents();\n var blockers = createEvents();\n\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), '');\n }\n\n function getBaseHref() {\n var base = document.querySelector('base');\n var href = '';\n\n if (base && base.getAttribute('href')) {\n var url = window.location.href;\n var hashIndex = url.indexOf('#');\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href;\n }\n\n function createHref(to) {\n return getBaseHref() + '#' + (typeof to === 'string' ? to : createPath(to));\n }\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n hash: '',\n search: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function getHistoryStateAndUrl(nextLocation, index) {\n return [{\n usr: nextLocation.state,\n key: nextLocation.key,\n idx: index\n }, createHref(nextLocation)];\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction) {\n action = nextAction;\n\n var _getIndexAndLocation7 = getIndexAndLocation();\n\n index = _getIndexAndLocation7[0];\n location = _getIndexAndLocation7[1];\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(nextLocation.pathname.charAt(0) === '/', \"Relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr3 = getHistoryStateAndUrl(nextLocation, index + 1),\n historyState = _getHistoryStateAndUr3[0],\n url = _getHistoryStateAndUr3[1]; // TODO: Support forced reloading\n // try...catch because iOS limits us to 100 pushState calls :/\n\n\n try {\n globalHistory.pushState(historyState, '', url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n applyTx(nextAction);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(nextLocation.pathname.charAt(0) === '/', \"Relative pathnames are not supported in hash history.replace(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr4 = getHistoryStateAndUrl(nextLocation, index),\n historyState = _getHistoryStateAndUr4[0],\n url = _getHistoryStateAndUr4[1]; // TODO: Support forced reloading\n\n\n globalHistory.replaceState(historyState, '', url);\n applyTx(nextAction);\n }\n }\n\n function go(delta) {\n globalHistory.go(delta);\n }\n\n var history = {\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n var unblock = blockers.push(blocker);\n\n if (blockers.length === 1) {\n window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n\n return function () {\n unblock(); // Remove the beforeunload listener so the document may\n // still be salvageable in the pagehide event.\n // See https://html.spec.whatwg.org/#unloading-documents\n\n if (!blockers.length) {\n window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n };\n }\n };\n return history;\n}\n/**\r\n * Memory history stores the current location in memory. It is designed for use\r\n * in stateful non-browser environments like tests and React Native.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory\r\n */\n\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options3 = options,\n _options3$initialEntr = _options3.initialEntries,\n initialEntries = _options3$initialEntr === void 0 ? ['/'] : _options3$initialEntr,\n initialIndex = _options3.initialIndex;\n var entries = initialEntries.map(function (entry) {\n var location = readOnly(_extends({\n pathname: '/',\n search: '',\n hash: '',\n state: null,\n key: createKey()\n }, typeof entry === 'string' ? parsePath(entry) : entry));\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: \" + JSON.stringify(entry) + \")\") : void 0;\n return location;\n });\n var index = clamp(initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1);\n var action = Action.Pop;\n var location = entries[index];\n var listeners = createEvents();\n var blockers = createEvents();\n\n function createHref(to) {\n return typeof to === 'string' ? to : createPath(to);\n }\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n search: '',\n hash: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction, nextLocation) {\n action = nextAction;\n location = nextLocation;\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in memory history.push(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n applyTx(nextAction, nextLocation);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in memory history.replace(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n entries[index] = nextLocation;\n applyTx(nextAction, nextLocation);\n }\n }\n\n function go(delta) {\n var nextIndex = clamp(index + delta, 0, entries.length - 1);\n var nextAction = Action.Pop;\n var nextLocation = entries[nextIndex];\n\n function retry() {\n go(delta);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n index = nextIndex;\n applyTx(nextAction, nextLocation);\n }\n }\n\n var history = {\n get index() {\n return index;\n },\n\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n return blockers.push(blocker);\n }\n };\n return history;\n} ////////////////////////////////////////////////////////////////////////////////\n// UTILS\n////////////////////////////////////////////////////////////////////////////////\n\nfunction clamp(n, lowerBound, upperBound) {\n return Math.min(Math.max(n, lowerBound), upperBound);\n}\n\nfunction promptBeforeUnload(event) {\n // Cancel the event.\n event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.\n\n event.returnValue = '';\n}\n\nfunction createEvents() {\n var handlers = [];\n return {\n get length() {\n return handlers.length;\n },\n\n push: function push(fn) {\n handlers.push(fn);\n return function () {\n handlers = handlers.filter(function (handler) {\n return handler !== fn;\n });\n };\n },\n call: function call(arg) {\n handlers.forEach(function (fn) {\n return fn && fn(arg);\n });\n }\n };\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\r\n * Creates a string URL path from the given pathname, search, and hash components.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath\r\n */\n\n\nfunction createPath(_ref) {\n var _ref$pathname = _ref.pathname,\n pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,\n _ref$search = _ref.search,\n search = _ref$search === void 0 ? '' : _ref$search,\n _ref$hash = _ref.hash,\n hash = _ref$hash === void 0 ? '' : _ref$hash;\n if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;\n if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;\n return pathname;\n}\n/**\r\n * Parses a string URL path into its separate pathname, search, and hash components.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath\r\n */\n\nfunction parsePath(path) {\n var parsedPath = {};\n\n if (path) {\n var hashIndex = path.indexOf('#');\n\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n var searchIndex = path.indexOf('?');\n\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport { Action, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, parsePath };\n//# sourceMappingURL=index.js.map\n","/**\n * Channel names: patterns, the topics they build, and the checks both go\n * through. Shared by the `Broadcast` facade (which builds the topic an emit\n * goes to), `ChannelRouter` (which builds the topic a socket may join) and the\n * fake (which matches a pattern against recorded topics), so the three can\n * never disagree on what `site.:siteId` with `{ siteId: \"abc\" }` is called.\n *\n * A pattern is dot-separated segments, each either a literal (`site`) or a\n * param (`:siteId`). A topic is the same with every param filled in:\n * `site.abc123`. Param values are restricted to `[A-Za-z0-9_-]`, so a value\n * can never contain a dot and add a segment, and a topic can always be read\n * back as exactly one pattern's.\n */\n\n/** The longest topic, in characters. */\nexport const MAX_TOPIC_LENGTH = 255;\n\n/** The longest event name, in characters. */\nexport const MAX_EVENT_NAME_LENGTH = 64;\n\nconst LITERAL_SEGMENT = /^[A-Za-z0-9_-]+$/;\nconst PARAM_SEGMENT = /^:[A-Za-z_][A-Za-z0-9_]*$/;\nconst PARAM_VALUE = /^[A-Za-z0-9_-]{1,128}$/;\nconst EVENT_NAME = /^[A-Za-z0-9_.:-]+$/;\n\n/** The names of a pattern's params: `\"site.:siteId\"` → `\"siteId\"`. */\nexport type ChannelParamNames<P extends string> = P extends `${infer Head}.${infer Rest}`\n ? SegmentParam<Head> | ChannelParamNames<Rest>\n : SegmentParam<P>;\n\ntype SegmentParam<S extends string> = S extends `:${infer Name}` ? Name : never;\n\n/** The params a pattern takes: `\"site.:siteId\"` → `{ siteId: string | number }`. */\nexport type ChannelParams<P extends string> = {\n [K in ChannelParamNames<P>]: string | number;\n};\n\n/**\n * `[]` for a pattern without params (or a concrete topic), `[params]` for one\n * with them, so `Broadcast.to(\"status\")` and `Broadcast.to(\"site.:siteId\",\n * { siteId })` both type-check and `Broadcast.to(\"site.:siteId\")` does not.\n */\nexport type ChannelParamsArgs<P extends string> = [ChannelParamNames<P>] extends [never]\n ? [params?: Record<string, never>]\n : [params: ChannelParams<P>];\n\n/**\n * A resolved channel: the topic sockets subscribe to, and the pattern it came\n * from when it was built from one. What `BroadcastEvent.channel()` returns and\n * `Broadcast.to()` accepts.\n */\nexport interface ChannelTarget {\n readonly topic: string;\n readonly pattern?: string;\n}\n\n/** A pattern, topic or param was refused. The message says which and why. */\nexport class InvalidChannelError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidChannelError\";\n }\n}\n\n/** Whether `value` is a `ChannelTarget` rather than a pattern string. */\nexport function isChannelTarget(value: unknown): value is ChannelTarget {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { topic?: unknown }).topic === \"string\"\n );\n}\n\n/** The segments of a pattern, checked. Throws `InvalidChannelError`. */\nexport function parsePattern(pattern: string): string[] {\n if (typeof pattern !== \"string\" || pattern.length === 0) {\n throw new InvalidChannelError(\"A channel pattern must be a non-empty string.\");\n }\n if (pattern.length > MAX_TOPIC_LENGTH) {\n throw new InvalidChannelError(\n `The channel pattern \"${pattern.slice(0, 40)}…\" is longer than ${MAX_TOPIC_LENGTH} characters.`,\n );\n }\n const segments = pattern.split(\".\");\n const seen = new Set<string>();\n for (const segment of segments) {\n if (PARAM_SEGMENT.test(segment)) {\n const name = segment.slice(1);\n if (seen.has(name)) {\n throw new InvalidChannelError(\n `The channel pattern \"${pattern}\" names the param \"${name}\" twice.`,\n );\n }\n seen.add(name);\n continue;\n }\n if (segment.startsWith(\"__\")) {\n throw new InvalidChannelError(\n `The channel \"${pattern}\" has the segment \"${segment}\". Segments starting ` +\n `with \"__\" are reserved for gemi (driver control messages).`,\n );\n }\n if (!LITERAL_SEGMENT.test(segment)) {\n throw new InvalidChannelError(\n `The channel pattern \"${pattern}\" has an invalid segment \"${segment}\". ` +\n `Segments are separated by dots and are either letters, digits, \"_\" ` +\n `and \"-\", or a param such as \":siteId\".`,\n );\n }\n }\n return segments;\n}\n\n/** The param names of a pattern, in order. */\nexport function patternParams(pattern: string): string[] {\n return parsePattern(pattern)\n .filter((segment) => segment.startsWith(\":\"))\n .map((segment) => segment.slice(1));\n}\n\n/**\n * The topic `pattern` names with `params` filled in. Every param must be\n * given, and nothing else: a missing one, an extra one, or a value outside\n * `[A-Za-z0-9_-]` throws `InvalidChannelError`, so a client can never steer a\n * subscription onto a topic its pattern does not describe.\n */\nexport function buildTopic(pattern: string, params: Record<string, unknown> = {}): string {\n const segments = parsePattern(pattern);\n const expected = new Set<string>();\n const topic = segments\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n const name = segment.slice(1);\n expected.add(name);\n const value = params[name];\n if (value === undefined || value === null) {\n throw new InvalidChannelError(`The channel \"${pattern}\" needs the param \"${name}\".`);\n }\n const text = typeof value === \"number\" && Number.isFinite(value) ? String(value) : value;\n if (typeof text !== \"string\" || !PARAM_VALUE.test(text)) {\n throw new InvalidChannelError(\n `The param \"${name}\" of the channel \"${pattern}\" must be 1 to 128 ` +\n `letters, digits, \"_\" or \"-\". Use a public id in a channel name.`,\n );\n }\n return text;\n })\n .join(\".\");\n\n for (const key of Object.keys(params)) {\n if (!expected.has(key)) {\n throw new InvalidChannelError(`The channel \"${pattern}\" has no param \"${key}\".`);\n }\n }\n if (topic.length > MAX_TOPIC_LENGTH) {\n throw new InvalidChannelError(\n `The topic built from \"${pattern}\" is longer than ${MAX_TOPIC_LENGTH} characters.`,\n );\n }\n return topic;\n}\n\n/** Checks a concrete topic (no params). Throws `InvalidChannelError`. */\nexport function assertTopic(topic: string): string {\n const segments = parsePattern(topic);\n if (segments.some((segment) => segment.startsWith(\":\"))) {\n throw new InvalidChannelError(\n `\"${topic}\" is a pattern, not a topic: pass its params, as in ` +\n `Broadcast.to(\"${topic}\", { ... }).`,\n );\n }\n return topic;\n}\n\n/** Checks an event name. Throws `InvalidChannelError`. */\nexport function assertEventName(event: string): string {\n if (\n typeof event !== \"string\" ||\n event.length === 0 ||\n event.length > MAX_EVENT_NAME_LENGTH ||\n !EVENT_NAME.test(event)\n ) {\n throw new InvalidChannelError(\n `The event name \"${String(event).slice(0, 40)}\" must be 1 to ` +\n `${MAX_EVENT_NAME_LENGTH} letters, digits, \"_\", \"-\", \".\" or \":\".`,\n );\n }\n return event;\n}\n\n/**\n * Whether `topic` is one `pattern` builds. A pattern without params matches\n * only itself, except `\"user\"`, which also matches every `user.<id>`: that is\n * the topic the router's `user` channel resolves to.\n */\nexport function topicMatches(pattern: string, topic: string): boolean {\n if (pattern === topic) return true;\n if (pattern === USER_CHANNEL)\n return topic.startsWith(`${USER_CHANNEL}.`) && topic.split(\".\").length === 2;\n const patternSegments = pattern.split(\".\");\n const topicSegments = topic.split(\".\");\n if (patternSegments.length !== topicSegments.length) return false;\n return patternSegments.every(\n (segment, i) =>\n segment === topicSegments[i] ||\n (segment.startsWith(\":\") && PARAM_VALUE.test(topicSegments[i])),\n );\n}\n\n/**\n * The channel `ChannelRouter` resolves from the session rather than from\n * params: a socket that subscribes to `\"user\"` joins `user.<its user's id>`.\n */\nexport const USER_CHANNEL = \"user\";\n\n/** The topic of a user's own channel. */\nexport function userTopic(user: { id: unknown } | string | number): string {\n const id = typeof user === \"object\" && user !== null ? user.id : user;\n return buildTopic(`${USER_CHANNEL}.:id`, { id: id as string | number });\n}\n","import { buildTopic, topicMatches } from \"../../services/broadcast/channels\";\nimport type { DeniedCode } from \"../../services/broadcast/protocol\";\nimport { channelKey } from \"./channelKey\";\nimport type {\n ChannelListener,\n ChannelParamValues,\n ChannelStatus,\n RealtimeSocket,\n} from \"./RealtimeClient\";\n\nexport interface FakeSubscription {\n pattern: string;\n params: ChannelParamValues;\n status: ChannelStatus;\n code: DeniedCode | null;\n}\n\ninterface FakeEntry extends FakeSubscription {\n key: string;\n listeners: Set<ChannelListener>;\n}\n\n/**\n * A socket for component tests: what `<Page socket={...}>` hands the\n * channel hooks instead of a WebSocket. Every subscription is `open` at\n * once; the test pushes events and resyncs by hand.\n *\n * ```tsx\n * const socket = fakeSocket();\n * render(<Page socket={socket}><SiteEditor /></Page>);\n * act(() => socket.emit(\"site.:siteId\", \"changed\", { pages: [\"/about\"] }));\n * act(() => socket.resync());\n * ```\n *\n * No resync is run on subscribe, unlike the real socket's ack: a test says\n * when one happens.\n */\nexport class FakeSocket implements RealtimeSocket {\n private entries = new Map<string, FakeEntry>();\n private status: ChannelStatus = \"open\";\n\n subscribe(pattern: string, params: ChannelParamValues, listener: ChannelListener): () => void {\n const key = channelKey(pattern, params);\n let entry = this.entries.get(key);\n if (!entry) {\n entry = {\n key,\n pattern,\n params: { ...params },\n status: this.status,\n code: null,\n listeners: new Set(),\n };\n this.entries.set(key, entry);\n }\n entry.listeners.add(listener);\n listener.onStatus?.(entry.status, entry.code);\n return () => {\n entry!.listeners.delete(listener);\n if (entry!.listeners.size === 0) this.entries.delete(key);\n };\n }\n\n /** The channels subscribed to right now. */\n get subscriptions(): FakeSubscription[] {\n return Array.from(this.entries.values()).map(({ pattern, params, status, code }) => ({\n pattern,\n params,\n status,\n code,\n }));\n }\n\n /**\n * Delivers `event` to the open subscriptions `channel` names: a pattern\n * (`\"site.:siteId\"`, every subscription to it, or only those with `params`\n * when given), or a concrete topic (`\"site.abc\"`).\n */\n emit(channel: string, event: string, data?: unknown, params?: ChannelParamValues): void {\n for (const entry of this.matching(channel, params)) {\n if (entry.status !== \"open\") continue;\n for (const listener of Array.from(entry.listeners)) listener.onEvent?.(event, data);\n }\n }\n\n /** Runs every matching subscription's resync (all when `channel` is left out). */\n resync(channel?: string, params?: ChannelParamValues): void {\n for (const entry of channel ? this.matching(channel, params) : this.entries.values()) {\n if (entry.status !== \"open\") continue;\n for (const listener of Array.from(entry.listeners)) listener.onResync?.();\n }\n }\n\n /** Sets every subscription's status (and the status new ones start in). */\n setStatus(status: ChannelStatus): void {\n this.status = status;\n for (const entry of this.entries.values()) this.update(entry, status, null);\n }\n\n /** Refuses the matching subscriptions with `code`. */\n deny(channel: string, code: DeniedCode = \"denied\", params?: ChannelParamValues): void {\n for (const entry of this.matching(channel, params)) this.update(entry, \"denied\", code);\n }\n\n private update(entry: FakeEntry, status: ChannelStatus, code: DeniedCode | null) {\n entry.status = status;\n entry.code = code;\n for (const listener of Array.from(entry.listeners)) listener.onStatus?.(status, code);\n }\n\n private matching(channel: string, params?: ChannelParamValues): FakeEntry[] {\n return Array.from(this.entries.values()).filter((entry) => {\n if (entry.pattern === channel) {\n return !params || channelKey(channel, params) === entry.key;\n }\n try {\n const topic =\n Object.keys(entry.params).length > 0\n ? buildTopic(entry.pattern, entry.params)\n : entry.pattern;\n // `\"user\"` is resolved to `user.<id>` by the server; any id matches.\n return topic === channel || (entry.pattern === \"user\" && topicMatches(\"user\", channel));\n } catch {\n return false;\n }\n });\n }\n}\n\n/** A `FakeSocket` for `<Page socket={...}>`. */\nexport function fakeSocket(): FakeSocket {\n return new FakeSocket();\n}\n","import {\n Suspense,\n useContext,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type PropsWithChildren,\n type ReactNode,\n} from \"react\";\nimport { ErrorBoundary, type FallbackProps } from \"react-error-boundary\";\nimport { Action, createMemoryHistory } from \"history\";\n\nimport type { User } from \"../auth/types\";\nimport { ClientRouterContext } from \"../client/ClientRouterContext\";\nimport { I18nProvider } from \"../client/I18nContext\";\nimport { ProgressManager } from \"../client/ProgressManager\";\nimport {\n QueryManagerContext,\n QueryManagerProvider,\n type QueryConfig,\n} from \"../client/QueryManagerContext\";\nimport {\n RouteStateProvider,\n type PageData,\n type RouteState,\n} from \"../client/RouteStateContext\";\nimport { RouteTransitionProvider } from \"../client/RouteTransitionProvider\";\nimport {\n ServerDataContext,\n type ServerDataContextValue,\n} from \"../client/ServerDataProvider\";\nimport { ThemeProvider } from \"../client/ThemeProvider\";\nimport type { ClientFeatureKey } from \"../client/rpc\";\nimport { FakeSocket } from \"../client/realtime/FakeSocket\";\nimport { followLive } from \"../client/realtime/live\";\nimport { liveModule } from \"../client/realtime/loader\";\nimport { RealtimeContext } from \"../client/realtime/RealtimeContext\";\nimport type { Breadcrumb } from \"../client/useBreadcrumbs\";\nimport { applyParams } from \"../utils/applyParams\";\nimport { Subject } from \"../utils/Subject\";\nimport { toVariantKey } from \"../utils/variantKey\";\n\n// A live query loads its subscription on first use in an app (#891). Under\n// `<Page>` it is here already, so a query on the `FakeSocket` subscribes in\n// its effect and a test sees events without waiting for a module to load.\nliveModule.current = { followLive };\n\n/**\n * A dictionary as `Dictionary.create` produces it: a name and a\n * `{ key: { locale: string } }` map.\n *\n * Typed structurally rather than as `Dictionary<T>` for two reasons. It keeps\n * `gemi/testing` from importing `gemi/i18n` — a server entry, which reaches the\n * `Lang` facade and through it the container. And it means an object literal of\n * the same shape is accepted, so a test never *has* to import the app's\n * dictionaries at all.\n *\n * Only `name` and `dictionary` are read — both plain data. `Dictionary`'s\n * server-only methods (`render`, `reference`, which throw once `window` is\n * defined) are never called from here.\n */\nexport interface PageDictionary {\n name: string;\n dictionary: Record<string, Record<string, string>>;\n}\n\nexport interface PageProps {\n /**\n * The URL the view is mounted at. A template (`/app/:orgId/chat`) is resolved\n * against `params`, so the same string can be pasted from the router.\n *\n * As in the app, on a direct load and after a navigation alike,\n * `useRoute().pathname` reports the template as given here and\n * `useLocation().pathname` the resolved URL.\n */\n pathname?: string;\n /** Route params, as the router would have parsed them out of `pathname`. */\n params?: Record<string, string>;\n /** `\"?tab=recent\"`, `\"tab=recent\"`, or `{ tab: \"recent\" }`. */\n searchParams?: string | Record<string, string | number | boolean>;\n hash?: string;\n /** The locale `useTranslator` and `useLocale` report. */\n locale?: string;\n /**\n * The app's default locale. Links and `useNavigate` omit the locale segment\n * for it, so leaving this equal to `locale` (the default) keeps hrefs\n * unprefixed — set it to seed a page being viewed in a non-default locale.\n */\n defaultLocale?: string;\n supportedLocales?: string[];\n /** The zone `useFormatter` formats dates in. Defaults to `UTC`, like an app with no `translation.timeZone`. */\n timeZone?: string;\n /**\n * Dictionaries the components under test translate against — the app's own,\n * or literals of the same shape.\n *\n * Note what importing the app's costs: `app/i18n/index.ts` imports\n * `gemi/i18n`, a server entry, so the test file pulls the container and\n * `node:async_hooks` into its module graph. Nothing there runs (and nothing\n * here calls it), so it is fine under any runner that has Node builtins —\n * vitest, `bun test` — and not under one that renders in a real browser. Use\n * `translations` there, which is the shape the client actually receives.\n */\n dictionaries?: PageDictionary[];\n /**\n * Translations for the current locale, already resolved: dictionary name →\n * key → string. This is the shape the server serializes onto the page, so it\n * is what the client reads at runtime — and it imports nothing.\n *\n * ```tsx\n * <Page translations={{ Chat: { greeting: \"Hello {{name}}\" } }}>\n * ```\n *\n * Merged over `dictionaries`, so the two compose: seed from the app's real\n * dictionary and override the one key a test is about.\n */\n translations?: Record<string, Record<string, string>>;\n /**\n * Data `useQuery` finds already cached, keyed by API path — the path passed\n * to `useQuery`, without the `/api` prefix the client adds when it fetches.\n * A key may carry a query string (`\"/lists?page=2\"`) to seed one search\n * variant.\n *\n * The cache is keyed by the *resolved* path, so a key's `:params` are\n * resolved against the page's `params` — and a key naming one the page does\n * not carry is an error, naming the key. That case is common enough to be\n * worth the loud failure: a query often takes its params from the call site\n * rather than the route (`useQuery(\"/orgs/:orgId/lists\", { params: { orgId } })`\n * with `orgId` in component state), and the right seed for it is the resolved\n * path, `\"/orgs/abc/lists\"`.\n *\n * Seeded at mount only: a component that mutates or refetches its data owns\n * the cache from then on.\n */\n queryData?: Record<string, unknown>;\n /** App-wide `useQuery` defaults, as `createRoot` threads them. */\n queryConfig?: QueryConfig;\n /**\n * What `useUser()` reports. Defaults to `null` — an anonymous visitor — and\n * either way the hook resolves from here without issuing a request.\n */\n user?: Partial<User> | null;\n /** What `useBreadcrumbs()` returns, in order. */\n breadcrumbs?: Breadcrumb[];\n /**\n * The `route.domains` group the page is served under, as `useDomain()`\n * reports it. Left out, `useDomain()` reads empty — the shape an app without\n * `route.domains` sees — and `useDomain().url()` throws, exactly as it does\n * there.\n *\n * `root` and `origin` default off the host, so the common case is one field:\n * `domain={{ host: \"acme.example.com\", params: { tenant: \"acme\" } }}`.\n */\n domain?: {\n host: string;\n group?: string;\n params?: Record<string, string>;\n custom?: boolean;\n root?: string;\n origin?: string;\n } | null;\n /**\n * What `useFeature()` reports, keyed by feature key. Anything left out reads\n * as off, exactly as an undeclared key does in a real request.\n *\n * A test seeds the *outcome*, not the declaration: `app/features` owns the\n * targeting and the rollout, and re-deriving those here would mean building a\n * request context — a user, a `session_id`, a bot verdict — to assert a\n * branch that only cares which way the feature came out. Cover the targeting\n * where it lives, with a server test.\n */\n features?: Partial<Record<ClientFeatureKey, boolean>>;\n /**\n * The theme `useTheme()` starts on. The app reads a visitor's stored choice\n * out of `localStorage`; a test has no session to have made one in, so this\n * seeds it without writing to storage. `setTheme` works from either.\n */\n theme?: \"light\" | \"dark\" | \"system\";\n /**\n * Fallback for the `Suspense` boundary wrapped around the children — the\n * stand-in for the view's own `Loading` export, which the real router\n * supplies. Defaults to `null`.\n */\n fallback?: ReactNode;\n /**\n * Renders in place of the children when one throws, mirroring a view's\n * `Error` export. Without it a thrown render (an errored suspense query,\n * say) propagates out of `render()` and fails the test, which is usually\n * what you want.\n */\n errorFallback?: ComponentType<FallbackProps>;\n /**\n * Called when something navigates — a `Link` click, `useNavigate().push`.\n * The navigation is reported, not performed: `<Page>` renders one route and\n * does not re-resolve the tree, so `useLocation()` keeps reporting the\n * pathname it was given.\n */\n onNavigate?: (href: string, action: \"push\" | \"replace\") => void;\n /**\n * The socket `useChannel`, `useChannelInvalidate` and `useQuery({ live })`\n * subscribe through: a `fakeSocket()` the test pushes events and resyncs\n * into. Left out, a fake of the page's own is used, so a component test\n * never opens a WebSocket.\n */\n socket?: FakeSocket;\n}\n\n/** `\"?a=b\"` (or `\"\"`) from any of the shapes `searchParams` accepts. */\nfunction toSearchString(search: PageProps[\"searchParams\"]): string {\n if (!search) return \"\";\n const query =\n typeof search === \"string\"\n ? search.replace(/^\\?/, \"\")\n : new URLSearchParams(\n Object.entries(search).map(([key, value]) => [key, String(value)]),\n ).toString();\n return query ? `?${query}` : \"\";\n}\n\n/**\n * The `:params` a seed key needs supplied. Wildcards (`:rest*`) are excluded —\n * `applyParams` drops those when missing, which is a resolution rather than a\n * failure.\n *\n * Optional params (`:id?`) cannot reach here at all: a key is split at its\n * first `?` to separate the search string, so `\"/lists/:folderId?\"` arrives as\n * the path `/lists/:folderId`. Seed the resolved path for those.\n */\nfunction requiredParamsOf(path: string): string[] {\n return Array.from(path.matchAll(/:([^/]+)/g), ([, name]) => name).filter(\n (name) => !name.endsWith(\"*\"),\n );\n}\n\n/**\n * Fails a `queryData` key whose `:params` the page does not carry, saying so\n * in terms of the key.\n *\n * Without this the two documented runners disagree, and neither is legible.\n * `applyParams` throws `Missing parameter: orgId` under `import.meta.env.DEV`\n * (vitest) — a router-utility stack trace out of `<Page>`'s render, before\n * anything mounts, naming nothing that appears in the test. Under `bun test`\n * that flag is falsy, so it logs and seeds the literal `/orgs/undefined/lists`\n * instead: the seed misses, the query goes to the network, and the assertion\n * runs against a loading state.\n *\n * The case is common because a query's params often come from the call site\n * rather than the route — `useQuery(\"/orgs/:orgId/lists\", { params: { orgId } })`\n * with `orgId` in component state. The cache is keyed by the *resolved* path,\n * so the way out is to seed that path directly.\n */\nfunction resolveSeedPath(\n key: string,\n rawPath: string,\n params: Record<string, string>,\n): string {\n const missing = requiredParamsOf(rawPath).filter(\n (name) => params[name] === undefined,\n );\n if (missing.length > 0) {\n throw new Error(\n `[gemi] <Page> cannot resolve the queryData key \"${key}\": no value for ` +\n `${missing.map((name) => `:${name}`).join(\", \")}. The query cache is ` +\n `keyed by the resolved path, so either add ${missing\n .map((name) => `\\`${name}\\``)\n .join(\", \")} to the page's \\`params\\`, or seed the resolved path ` +\n `(e.g. \"${applyParams(\n rawPath,\n Object.fromEntries(missing.map((name) => [name, \"123\"])),\n )}\") — which is what a query taking its params from component state ` +\n `reads under.`,\n );\n }\n return applyParams(rawPath, params);\n}\n\n/**\n * `queryData` in the shape the query cache seeds from: `{ [path]: { [variant]:\n * data } }`, the same payload `Query.prefetch` puts on a server-rendered page.\n */\nfunction toPrefetchedData(\n queryData: Record<string, unknown>,\n params: Record<string, string>,\n warned: Set<string>,\n) {\n const prefetchedData: Record<string, Record<string, unknown>> = {};\n for (const [key, data] of Object.entries(queryData)) {\n const [rawPath, rawSearch = \"\"] = key.split(\"?\");\n // Once per key per page, not once per render: this runs again on every\n // re-render, and a duplicated warning reads as a second mistake.\n if (rawPath.startsWith(\"/api/\") && !warned.has(key)) {\n warned.add(key);\n console.warn(\n `[gemi] queryData key \"${key}\" starts with /api. useQuery is keyed by ` +\n `the path you pass it — the /api prefix is added when it fetches — ` +\n `so this entry seeds a path no query reads.`,\n );\n }\n const path = resolveSeedPath(key, rawPath, params);\n prefetchedData[path] = {\n ...prefetchedData[path],\n [toVariantKey(rawSearch)]: data,\n };\n }\n return prefetchedData;\n}\n\n/**\n * `{ [locale]: { [dictionary]: { [key]: string } } }` — the payload\n * `Translator` serializes onto the page, which is the only form the client\n * ever sees. `dictionaries` are transposed into it (they are keyed the other\n * way round, by key then locale); `translations` is already in it and lands\n * under `locale`, last, so it wins.\n */\nfunction toClientDictionary(\n dictionaries: PageDictionary[],\n locales: string[],\n locale: string,\n translations: Record<string, Record<string, string>>,\n): Record<string, Record<string, Record<string, string>>> {\n const clientDictionary: Record<\n string,\n Record<string, Record<string, string>>\n > = {};\n for (const supported of locales) {\n clientDictionary[supported] ??= {};\n }\n for (const { name, dictionary } of dictionaries) {\n for (const [key, byLocale] of Object.entries(dictionary ?? {})) {\n for (const [dictLocale, translation] of Object.entries(byLocale ?? {})) {\n clientDictionary[dictLocale] ??= {};\n clientDictionary[dictLocale][name] ??= {};\n clientDictionary[dictLocale][name][key] = translation;\n }\n }\n }\n for (const [name, keys] of Object.entries(translations)) {\n clientDictionary[locale] ??= {};\n clientDictionary[locale][name] = {\n ...clientDictionary[locale][name],\n ...keys,\n };\n }\n return clientDictionary;\n}\n\n/**\n * Mounts a component with the inputs a view normally arrives with — route\n * params, the current locale and its dictionaries, prefetched query data, the\n * signed-in user — so a unit test can assert what it renders rather than only\n * its empty state.\n *\n * ```tsx\n * import { render, screen } from \"@testing-library/react\";\n * import { Page } from \"gemi/testing\";\n *\n * render(\n * <Page\n * pathname=\"/app/:orgId/chat\"\n * params={{ orgId: \"abc\" }}\n * queryData={{ \"/organizations/:orgId/messages\": [{ id: 1, body: \"hi\" }] }}\n * dictionaries={[ChatDictionary]}\n * >\n * <OrgChat />\n * </Page>,\n * );\n *\n * expect(screen.getByText(\"hi\")).toBeDefined();\n * ```\n *\n * It is a plain component, so it composes with any renderer — Testing\n * Library's `render`, `react-test-renderer`, or `renderToString`.\n *\n * Two things it does not do.\n *\n * It does not route: there is no view tree and no route manifest behind it, so\n * a navigation is reported through `onNavigate` rather than resolved. To\n * assert the page *after* one, render a second `<Page>`.\n *\n * And under `renderToString` it renders the server's own no-data branch for an\n * *unseeded* query rather than suspending — deliberately, because suspending\n * there is the streaming server's job: `createRoot` threads the request's\n * `ServerQueryStore` through `ServerQueryContext`, and that store is what runs\n * the route handler. A harness has no request and no handler to run, so there\n * is nothing to suspend on. Seeded queries render their data on the server\n * exactly as they do in the browser; unseeded ones behave as a route with no\n * `Query.prefetch` does, framework warning included.\n */\nexport const Page = (props: PropsWithChildren<PageProps>) => {\n const {\n children,\n pathname: routePath = \"/\",\n params = {},\n searchParams,\n hash = \"\",\n locale = \"en-US\",\n defaultLocale = locale,\n timeZone = \"UTC\",\n dictionaries = [],\n translations = {},\n queryData = {},\n queryConfig,\n user = null,\n breadcrumbs = [],\n domain = null,\n features = {},\n theme,\n fallback = null,\n errorFallback,\n onNavigate,\n socket,\n } = props;\n const [ownSocket] = useState(() => new FakeSocket());\n\n // The caller's list, in the caller's order — a language switcher maps over\n // it, so hoisting the page's own locale to the front would reorder the\n // rendered options. The defaults are appended, only to guarantee presence.\n const supportedLocales = useMemo(\n () =>\n Array.from(\n new Set([...(props.supportedLocales ?? []), defaultLocale, locale]),\n ),\n [props.supportedLocales, defaultLocale, locale],\n );\n const pathname = applyParams(routePath, params) || \"/\";\n // `root` defaults to the host minus its first label, so a tenant subdomain\n // needs only its host; `origin` to https on that host. Either can be given\n // outright when the test is about the other.\n const domainValue = useMemo(() => {\n if (!domain) {\n return null;\n }\n const labels = domain.host.split(\".\");\n return {\n host: domain.host,\n group: domain.group ?? \"\",\n params: domain.params ?? {},\n custom: domain.custom ?? false,\n root:\n domain.root ?? (labels.length > 2 ? labels.slice(1).join(\".\") : domain.host),\n origin: domain.origin ?? `https://${domain.host}`,\n };\n }, [domain]);\n const search = toSearchString(searchParams);\n // The URL's locale segment, which the default locale does not get.\n const urlLocaleSegment = locale === defaultLocale ? null : locale;\n\n const dictionary = useMemo(\n () =>\n toClientDictionary(dictionaries, supportedLocales, locale, translations),\n [dictionaries, supportedLocales, locale, translations],\n );\n\n // Keys that have already drawn a warning, so a re-render does not repeat it.\n const warnedRef = useRef<Set<string>>(new Set());\n const prefetchedData = useMemo(() => {\n const seeded = toPrefetchedData(queryData, params, warnedRef.current);\n // `useUser` reads `/auth/me` like any other query. Seeding it — with `null`\n // for the anonymous default — is what keeps a component test off the\n // network for a hook nothing in the test asked for.\n seeded[\"/auth/me\"] ??= { \"\": user ?? null };\n return seeded;\n }, [queryData, params, user]);\n\n // Keyed by `${view}:${route template}` in the router's cache, which is what\n // `useBreadcrumbs` reads through `useRoute()`; the view names are ours to\n // choose here, and only their order reaches `useBreadcrumbs`.\n const { breadcrumbViews, breadcrumbsCache, breadcrumbsRecord } =\n useMemo(() => {\n const views = breadcrumbs.map((_, index) => `breadcrumb-${index}`);\n const cache = new Map<string, Breadcrumb>(\n breadcrumbs.map((breadcrumb, index) => [\n `${views[index]}:${routePath}`,\n breadcrumb,\n ]),\n );\n return {\n breadcrumbViews: views,\n breadcrumbsCache: cache,\n breadcrumbsRecord: Object.fromEntries(cache),\n };\n }, [breadcrumbs, routePath]);\n\n const [isNavigatingSubject] = useState(() => new Subject<boolean>(false));\n const [progressManager] = useState(\n () => new ProgressManager(isNavigatingSubject),\n );\n const [history] = useState(() =>\n createMemoryHistory({ initialEntries: [`${pathname}${search}${hash}`] }),\n );\n\n const routeState: RouteState & PageData = useMemo(\n () => ({\n views: [],\n params,\n search,\n state: {},\n pathname,\n hash,\n action: null,\n routePath,\n locale: urlLocaleSegment,\n data: {},\n i18n: {\n currentLocale: locale,\n dictionary,\n supportedLocales,\n defaultLocale,\n timeZone,\n },\n prefetchedData,\n breadcrumbs: breadcrumbsRecord,\n features: features as Record<string, boolean>,\n appId: \"test\",\n }),\n [\n params,\n search,\n pathname,\n hash,\n routePath,\n urlLocaleSegment,\n locale,\n dictionary,\n supportedLocales,\n defaultLocale,\n timeZone,\n prefetchedData,\n breadcrumbsRecord,\n features,\n ],\n );\n\n const [routerSubject] = useState(() => new Subject<RouteState>(routeState));\n\n const onNavigateRef = useRef(onNavigate);\n onNavigateRef.current = onNavigate;\n // Subscribed during render, not in an effect, because React flushes child\n // effects before parent ones — and mount-time navigation is a real pattern:\n // `<Redirect>` pushes from its own mount effect, as does any auth guard. A\n // listener registered in `<Page>`'s effect is not there yet when those fire,\n // so `onNavigate` would silently miss exactly the redirects a test most\n // wants to assert. Ref-guarded, so React's double-invoke registers one.\n //\n // Nothing unsubscribes: this history is created per `<Page>` and reachable\n // from nowhere else, so it is collected with the page it belongs to.\n const listeningRef = useRef(false);\n if (!listeningRef.current) {\n listeningRef.current = true;\n history.listen(({ location, action }) => {\n const href = `${location.pathname}${location.search}${location.hash}`;\n onNavigateRef.current?.(\n href,\n action === Action.Replace ? \"replace\" : \"push\",\n );\n });\n }\n\n const serverData: ServerDataContextValue = useMemo(\n () => ({\n routeManifest: {},\n pageData: {},\n breadcrumbs: breadcrumbsRecord,\n prefetchedData,\n // As the server sends it: `pathname` is the route template and\n // `currentPath` the URL, locale segment included.\n router: {\n pathname: routePath,\n params,\n currentPath: `${urlLocaleSegment ? `/${urlLocaleSegment}` : \"\"}${pathname}`,\n is404: false,\n searchParams: search,\n urlLocaleSegment,\n domain: domainValue,\n },\n i18n: {\n dictionary,\n currentLocale: locale,\n supportedLocales,\n defaultLocale,\n timeZone,\n },\n componentTree: [],\n auth: { user: user as User },\n features: features as Record<string, boolean>,\n __csrf: \"test-csrf-token\",\n cssManifest: {},\n modulePreloadManifest: {},\n meta: {},\n appId: \"test\",\n }),\n [\n breadcrumbsRecord,\n prefetchedData,\n pathname,\n params,\n routePath,\n search,\n urlLocaleSegment,\n dictionary,\n locale,\n supportedLocales,\n defaultLocale,\n timeZone,\n user,\n features,\n ],\n );\n\n // Everything the router hooks read, inert: nothing here fetches, preloads or\n // resolves a route, but every hook finds the shape it expects rather than an\n // empty context to crash on.\n const [viewEntriesSubject] = useState(() => new Subject<string[]>([]));\n const routerContext = useMemo(\n () => ({\n viewEntriesSubject,\n history,\n updatePageData: () => {},\n getPageData: () => ({}),\n getScrollPosition: () => 0,\n getViewPathsFromPathname: () => breadcrumbViews,\n getRoutePathnameFromHref: (href: string) => href,\n isNavigatingSubject,\n setNavigationAbortController: () => {},\n progressManager,\n fetchRouteCSS: async () => {},\n preloadRouteModules: () => {},\n prefetchRoute: async () => {},\n takePrefetched: () => null,\n clearPrefetchCache: () => {},\n breadcrumbsCache,\n routerSubject,\n urlLocaleSegment,\n }),\n [\n viewEntriesSubject,\n history,\n breadcrumbViews,\n isNavigatingSubject,\n progressManager,\n breadcrumbsCache,\n routerSubject,\n urlLocaleSegment,\n ],\n );\n\n return (\n <ThemeProvider theme={theme}>\n <ServerDataContext.Provider value={serverData}>\n <I18nProvider>\n <QueryManagerProvider queryConfig={queryConfig}>\n <ClientRouterContext.Provider value={routerContext}>\n <RouteTransitionProvider\n isPending={false}\n isFetching={false}\n transitionPath={[\"\", pathname]}\n >\n <RouteStateProvider state={routeState}>\n <RealtimeContext.Provider value={socket ?? ownSocket}>\n <Boundary\n errorFallback={errorFallback}\n fallback={fallback}\n resetKey={pathname}\n >\n {children}\n </Boundary>\n </RealtimeContext.Provider>\n </RouteStateProvider>\n </RouteTransitionProvider>\n </ClientRouterContext.Provider>\n </QueryManagerProvider>\n </I18nProvider>\n </ServerDataContext.Provider>\n </ThemeProvider>\n );\n};\n\n/**\n * The `Suspense` boundary every view renders inside, and — when the test\n * supplies a fallback for it — the error boundary too.\n *\n * `onReset={clearErrors}` is the part that has to be here rather than inline\n * above: it needs `QueryManagerContext`, and it is what makes a view's real\n * `Error` export testable. A fallback whose \"Try again\" calls\n * `resetErrorBoundary()` re-renders the child, and `useQuery` reads the\n * failure still stored on the `QueryResource` and throws it straight back —\n * so without this the fallback never goes away and the retry path that works\n * in the app cannot be exercised. `ClientRouter`'s own boundary wires exactly\n * this pair.\n */\nconst Boundary = (\n props: PropsWithChildren<{\n errorFallback?: ComponentType<FallbackProps>;\n fallback: ReactNode;\n resetKey: string;\n }>,\n) => {\n const { errorFallback: ErrorFallback, fallback, resetKey, children } = props;\n const { clearErrors } = useContext(QueryManagerContext);\n const content = <Suspense fallback={fallback}>{children}</Suspense>;\n\n if (!ErrorFallback) {\n return content;\n }\n\n return (\n <ErrorBoundary\n FallbackComponent={ErrorFallback}\n resetKeys={[resetKey]}\n onReset={clearErrors}\n >\n {content}\n </ErrorBoundary>\n );\n};\n","/**\n * The browser side of islands, shared by the Vite plugin (which builds it), the\n * servers (which point the loader at it) and the tests.\n *\n * No imports: the Vite plugin is built on its own and the servers load it at\n * boot, so this file stays plain strings.\n */\n\n/**\n * The module that hydrates islands: React, `react-dom/client` and the small\n * `h(marker, Component)` below. A virtual module of gemi's Vite plugin that\n * every island entry imports, so the islands on a page share one copy of\n * React, in one chunk.\n */\nexport const ISLAND_RUNTIME_ID = \"virtual:gemi-island-runtime\";\n\n/** What `resolveId` turns `ISLAND_RUNTIME_ID` into (Vite's virtual-module convention). */\nexport const RESOLVED_ISLAND_RUNTIME_ID = `\\0${ISLAND_RUNTIME_ID}`;\n\n/**\n * The query that turns a module into its island entry: `Counter.tsx?gemi-island`\n * is a module of the plugin's that re-exports `Counter.tsx` as `m` next to the\n * runtime's `h`. It is what a static page imports for an island, and so it\n * is what the client manifest lists, keyed `app/…/Counter.tsx?gemi-island`,\n * with React and `react-dom/client` among its imports.\n */\nexport const ISLAND_ENTRY_QUERY = \"?gemi-island\";\n\n/** The island entry module for `file` (an absolute path or a root-relative URL). */\nexport function islandEntrySource(file: string) {\n return `import * as m from ${JSON.stringify(file)};\nexport { m };\nexport { h } from ${JSON.stringify(ISLAND_RUNTIME_ID)};\n`;\n}\n\n/**\n * `h(marker, Component)`: hydrates one `<gemi-island>` marker with the island's\n * component and the props the server serialised into `data-props`.\n *\n * The island's static children were rendered on the server into a\n * `<gemi-slot>` (the first one that belongs to this marker, not to an island\n * nested in it). They are handed back to the component as that same element\n * with the server's HTML, so hydration matches and React leaves them alone.\n *\n * `data-uid` is the `identifierPrefix` the server rendered the island with, so\n * `useId` agrees on both sides and two islands never share an id.\n *\n * When the page carries `#gemi-island-i18n` (its islands read the page's\n * locale or dictionaries, #1095), the dictionaries in it are seeded into the\n * dictionary registry through `__GEMI_DICT__` and the island's root gets the\n * locale and zone in `IslandI18nContext` (found on `globalThis`, where\n * `gemi/client` puts it), so `useDictionary` resolves synchronously, with the\n * strings the server rendered, and fetches nothing. An island that does not\n * import `gemi/client` has no such context to read, and is left as it was.\n *\n * The island's root reads queries through the cache the page's islands\n * share (found on `globalThis` under `gemi.islandQueries`, where `gemi/client`\n * puts it, #1155). When the page carries `#gemi-island-queries` (its islands\n * read queries the request prefetched), that `{ path: { variantKey: data } }`\n * payload seeds the cache first, so `useQuery` hydrates with the server's\n * data and does not refetch it.\n *\n * Written as a function body with `createElement` and `hydrateRoot` free, so a\n * test can run it against real React without a bundler.\n */\nexport const ISLAND_HYDRATE_SOURCE = `function h(marker, Component) {\n if (typeof Component !== \"function\" && (typeof Component !== \"object\" || Component === null)) {\n throw new Error(\"gemi: island module has no component export for \" + marker.outerHTML.slice(0, 80));\n }\n const json = marker.getAttribute(\"data-props\");\n const props = json ? JSON.parse(json) : {};\n let slot = null;\n for (const candidate of marker.querySelectorAll(\"gemi-slot\")) {\n if (candidate.closest(\"gemi-island\") === marker) {\n slot = candidate;\n break;\n }\n }\n const children = slot\n ? [createElement(\"gemi-slot\", {\n style: { display: \"contents\" },\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: { __html: slot.innerHTML },\n })]\n : [];\n let element = createElement(Component, props, ...children);\n const i18n = document.getElementById(\"gemi-island-i18n\");\n const context = globalThis[Symbol.for(\"gemi.islandI18n\")];\n if (i18n && context) {\n const payload = (i18n.p = i18n.p || JSON.parse(i18n.textContent));\n const dictionaries = (self.__GEMI_DICT__ = self.__GEMI_DICT__ || []);\n for (const entry of payload.dictionaries || []) dictionaries.push(entry);\n element = createElement(context.Provider, {\n value: { currentLocale: payload.currentLocale, defaultLocale: payload.defaultLocale, timeZone: payload.timeZone },\n }, element);\n }\n const cache = globalThis[Symbol.for(\"gemi.islandQueries\")];\n if (cache) {\n const queries = document.getElementById(\"gemi-island-queries\");\n if (queries) cache.seed((queries.p = queries.p || JSON.parse(queries.textContent)));\n element = createElement(cache.Provider, null, element);\n }\n return hydrateRoot(marker, element, {\n identifierPrefix: marker.getAttribute(\"data-uid\") || undefined,\n });\n}`;\n\n/** The runtime module's source, as the plugin serves and builds it. */\nexport const ISLAND_RUNTIME_SOURCE = `import { createElement } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nexport ${ISLAND_HYDRATE_SOURCE}\n`;\n\n/**\n * The island loader, inlined into a static document that uses islands.\n *\n * Kept byte-for-byte constant (the per-page island table travels in a\n * separate `<script type=\"application/json\">`, which a Content Security Policy\n * does not treat as script), so a strict policy can allow it by hash:\n * `script-src 'sha256-…'` with `ISLAND_LOADER_CSP_HASH`. Everything it loads\n * is a plain `import()` of a same-origin (or asset-base) file.\n *\n * The table is `{ i: [{ s: entry URL, e: export, l: load }] }` and each\n * marker's `data-island` indexes `i`. Per marker, on its schedule: import the\n * island's entry (the module as `m`, the runtime's `h`), then\n * `h(marker, m[export])`, which calls `hydrateRoot`. A failure is logged and\n * leaves the server-rendered markup in place.\n */\nexport const ISLAND_LOADER_SOURCE =\n 'const d=document,c=JSON.parse(d.getElementById(\"gemi-islands\").textContent),' +\n \"w=f=>(window.requestIdleCallback||setTimeout)(f),\" +\n \"m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};\" +\n 'for(const e of d.querySelectorAll(\"gemi-island\")){const o=c.i[e.dataset.island];if(!o)continue;' +\n 'if(o.l==\"eager\")m(e,o);else if(o.l==\"idle\"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));' +\n \"else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}\";\n","// Generated by `bun scripts/build-static-navigation.ts` from\n// `internal/staticNavigation/runtime.js`. Do not edit; edit the source and regenerate.\n// No imports: `gemi/testing` (a browser bundle) and `gemi stats` read it too.\n\n/** The sha-256 of the source this was built from, so a test can tell it is stale. */\nexport const STATIC_NAVIGATION_SOURCE_HASH = \"7150f8f2959c2cd5f5b6f784452c2aa520d7d06cbe52402b2de7bc85317ac3d6\";\n\n/**\n * The navigation runtime (with the island loader) a static view with\n * `.static({ navigation })` inlines. Byte-for-byte constant.\n */\nexport const STATIC_NAVIGATION_SOURCE =\n \"var r=document,i=window,a=history;i.__gemi_nav?.d();var C=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:C.signal,...s}),q=i.__gemi_nav={d:()=>C.abort()},y=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},L=(t)=>{let e=t.getElementById(\\\"gemi-islands\\\");return e?JSON.parse(e.textContent):{i:[]}},D=(t,e)=>{for(let n of t.querySelectorAll(\\\"gemi-island\\\")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l==\\\"eager\\\")y(n,s);else if(s.l==\\\"idle\\\"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>y(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),y(n,s)});for(let m of n.children)l.observe(m)}}},R='meta[name=\\\"gemi-static\\\"]',A=\\\"style:not([data-gemi-fonts])\\\",T=A+\\\",link[rel=stylesheet]\\\",K=`head>${A},body>${A},link[rel=stylesheet]`,I='meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type=\\\"application/ld+json\\\"]',w=(t)=>t.querySelector(R)?.content,O=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split(\\\"#\\\")[0],N=O(r),p=r.createElement(\\\"div\\\");p.setAttribute(\\\"aria-live\\\",\\\"polite\\\");p.style.cssText=\\\"position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap\\\";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent(\\\"gemi:page-load\\\",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:\\\"text/html\\\",\\\"x-gemi-navigate\\\":\\\"1\\\"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\\\/html/.test(s.headers.get(\\\"content-type\\\"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.(\\\"a[href]\\\"),n=e?.getAttribute(\\\"target\\\");if(!e||n&&n!=\\\"_self\\\"||e.hasAttribute(\\\"download\\\")||/(^|\\\\s)external(\\\\s|$)/i.test(e.getAttribute(\\\"rel\\\"))||e.closest(\\\"[data-gemi-reload]\\\"))return;let s=new URL(e.getAttribute(\\\"href\\\"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes(\\\"#\\\")&&c(s)==c(location)))return s},v={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},\\\"\\\"),P=c(location),b=0,Y=(t)=>{if(!t.hasAttribute(\\\"tabindex\\\"))t.setAttribute(\\\"tabindex\\\",\\\"-1\\\"),t.addEventListener(\\\"blur\\\",()=>t.removeAttribute(\\\"tabindex\\\"),{once:!0});t.focus({preventScroll:!0})},j=(t)=>{let e=r.body,n=t.body,s=L(t),l=r.documentElement;r.title=t.title;for(let o of[\\\"lang\\\",\\\"dir\\\"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll(\\\"link[rel=modulepreload]\\\")].map((o)=>o.getAttribute(\\\"href\\\")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll(\\\"link[rel=modulepreload]\\\")].filter((o)=>!m.has(o.getAttribute(\\\"href\\\"))));let d=new Map([...e.querySelectorAll(\\\"[data-gemi-persist]\\\")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll(\\\"[data-gemi-persist]\\\")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll(\\\"gemi-island\\\")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),D(e,s)},H=async(t,e)=>{let n=++b,s=!e&&v[a.state?.g];a.scrollRestoration=\\\"manual\\\";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,\\\"text/html\\\");if(w(d)==null||w(d)!=w(r)||O(d)!=N)throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},\\\"\\\",o.href)}P=c(location),j(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:\\\"instant\\\"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:\\\"instant\\\"});if(e)Y(g||r.querySelector(\\\"h1\\\")||r.querySelector(\\\"main\\\")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,\\\"click\\\",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent(\\\"gemi:before-navigate\\\",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),v[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,\\\"popstate\\\",()=>{if(b++,c(location)==P){let t=v[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:\\\"instant\\\"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,\\\"hashchange\\\",E);h(i,\\\"scroll\\\",()=>a.state?.g&&(v[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(R)?.dataset.prefetch==\\\"none\\\"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,\\\"pointerover\\\",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,\\\"pointerout\\\",()=>clearTimeout(S));h(r,\\\"focusin\\\",x);h(r,\\\"touchstart\\\",x,{passive:!0});E();D(r,L(r));_(!0);\";\n","import { createElement } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { ISLAND_HYDRATE_SOURCE } from \"../internal/islandRuntime\";\nimport { STATIC_NAVIGATION_SOURCE } from \"../internal/staticNavigationRuntime\";\n\n/**\n * One page `renderStaticDocument` serves to the navigation runtime: its HTML, or\n * a response of another kind to see the runtime fall back to a full load.\n */\nexport interface StaticTestPage {\n html?: string;\n /** Default 200. */\n status?: number;\n /** Default `text/html; charset=utf-8`. */\n contentType?: string;\n /** The URL the response ends at, as after a redirect. Default: the one asked for. */\n url?: string;\n}\n\nexport interface StaticDocumentOptions {\n /** The document's URL, resolved against the test window's origin. Default `/`. */\n url?: string;\n /**\n * What the runtime's `fetch` gets, by path (`/about`, `/about?x=1`) or full\n * URL: HTML, a `StaticTestPage`, or a function for anything else. A URL\n * not listed is a 404.\n */\n pages?:\n | Record<string, string | StaticTestPage>\n | ((url: URL) => string | StaticTestPage | Promise<string | StaticTestPage>);\n /**\n * The island modules, by the entry URL the page's island table names (`s`):\n * each a module whose exports include the islands' components. Hydrated\n * with React, as `<module>?gemi-island` would.\n */\n islands?: Record<string, Record<string, unknown>>;\n /**\n * Run the page's document script (`.static({ script })`) once, before the\n * runtime starts, as the browser would. Off by default. Scripts of pages\n * swapped in later never run, as in the browser.\n */\n documentScript?: boolean;\n}\n\n/** How a navigation ended. */\nexport type StaticNavigationResult =\n /** The runtime swapped the fetched page in. */\n | { kind: \"swap\"; url: string }\n /** The runtime gave up on a swap and asked for a full page load of `url`. */\n | { kind: \"full-load\"; url: string }\n /** The runtime left the click alone: the browser would follow the link itself. */\n | { kind: \"native\" };\n\nexport interface StaticDocumentHandle {\n /**\n * Clicks the page's first `<a>` whose `href` attribute is `href` and waits\n * for the outcome. Throws when there is no such link.\n */\n navigate(href: string, init?: MouseEventInit): Promise<StaticNavigationResult>;\n /** `history.back()`, and waits for the runtime to show that entry. */\n back(): Promise<StaticNavigationResult>;\n /** Every URL the runtime fetched, prefetches included, in order. */\n requests: string[];\n /** Every full page load the runtime asked for. */\n fullLoads: string[];\n /** Stops the runtime and restores what the helper stubbed. */\n dispose(): void;\n}\n\nconst hydrate = new Function(\n \"createElement\",\n \"hydrateRoot\",\n `${ISLAND_HYDRATE_SOURCE};return h;`,\n)(createElement, hydrateRoot) as (marker: Element, component: unknown) => unknown;\n\n/**\n * Puts a static document (`.static({ navigation })`) into the test's DOM and\n * starts its navigation runtime against stubbed pages, so a test can check that\n * a site's links are followed client-side, and what the next page looks like.\n * Needs a DOM (`// @vitest-environment jsdom` or `happy-dom`).\n *\n * ```ts\n * const html = await (await render(\"/\")).text(); // the page, from your app\n * const page = renderStaticDocument(html, { pages: { \"/about\": aboutHtml } });\n * expect(await page.navigate(\"/about\")).toEqual({ kind: \"swap\", url: \"http://localhost:3000/about\" });\n * expect(document.querySelector(\"h1\")!.textContent).toBe(\"About\");\n * page.dispose();\n * ```\n *\n * The document's own scripts do not run (the helper runs the runtime itself,\n * and the document script with `documentScript: true`), and a link the runtime leaves alone is not followed. Islands hydrate\n * asynchronously, as in a browser: wrap what follows in `act`, or wait for it.\n */\nexport function renderStaticDocument(\n html: string,\n options: StaticDocumentOptions = {},\n): StaticDocumentHandle {\n const requests: string[] = [];\n const fullLoads: string[] = [];\n let settle: ((result: StaticNavigationResult) => void) | undefined;\n const outcome = () =>\n new Promise<StaticNavigationResult>((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(\"the navigation did not finish in 5 s\")), 5000);\n settle = (result) => {\n clearTimeout(timer);\n settle = undefined;\n resolve(result);\n };\n });\n\n history.replaceState(null, \"\", options.url ?? \"/\");\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n const documentScript = options.documentScript\n ? parsed.querySelector(\"head > script[data-gemi-script]\")?.textContent\n : undefined;\n for (const script of Array.from(parsed.querySelectorAll(\"script\"))) {\n if (!/json/.test(script.type)) script.remove();\n }\n // Removed, then appended: happy-dom refuses a second root element, which\n // `replaceChild` (insert, then remove) would make for a moment (#1102).\n const root = document.importNode(parsed.documentElement, true);\n document.removeChild(document.documentElement);\n document.appendChild(root);\n\n const fullLoad = (url: string) => {\n fullLoads.push(url);\n settle?.({ kind: \"full-load\", url });\n };\n const location = {\n get href() {\n return window.location.href;\n },\n get origin() {\n return window.location.origin;\n },\n assign: (url: string) => fullLoad(new URL(url, window.location.href).href),\n reload: () => fullLoad(window.location.href),\n };\n\n const pages = options.pages ?? {};\n const fetch = async (input: string) => {\n const url = new URL(input, window.location.href);\n requests.push(url.href);\n const page =\n typeof pages === \"function\"\n ? await pages(url)\n : (pages[url.href] ?? pages[url.pathname + url.search]);\n const spec: StaticTestPage =\n page === undefined\n ? { status: 404, html: \"not found\", contentType: \"text/plain\" }\n : typeof page === \"string\"\n ? { html: page }\n : page;\n const response = new Response(spec.html ?? \"\", {\n status: spec.status ?? 200,\n headers: { \"content-type\": spec.contentType ?? \"text/html; charset=utf-8\" },\n });\n Object.defineProperty(response, \"url\", { value: new URL(spec.url ?? url.href, url).href });\n return response;\n };\n\n const importIsland = async (src: string) => {\n const module = options.islands?.[src];\n if (!module) throw new Error(`renderStaticDocument: no island module for ${src} in options.islands`);\n return { m: module, h: hydrate };\n };\n\n // The runtime announces a click it takes with `gemi:before-navigate`; one\n // it does not take (or one a listener cancelled) is the browser's, which\n // jsdom would try (and fail) to follow, so it is stopped here, on `window`,\n // after every listener on the way.\n let announced: Event | undefined;\n const onBeforeNavigate = (event: Event) => {\n announced = event;\n };\n document.addEventListener(\"gemi:before-navigate\", onBeforeNavigate);\n const onClick = (event: Event) => {\n const taken = announced !== undefined && !announced.defaultPrevented;\n announced = undefined;\n if (taken || !(event.target as Element).closest?.(\"a[href]\")) return;\n event.preventDefault();\n settle?.({ kind: \"native\" });\n };\n window.addEventListener(\"click\", onClick);\n const onPageLoad = (event: Event) => {\n const detail = (event as CustomEvent<{ url: string; initial: boolean }>).detail;\n if (!detail.initial) settle?.({ kind: \"swap\", url: detail.url });\n };\n document.addEventListener(\"gemi:page-load\", onPageLoad);\n\n // Not implemented by jsdom.\n const scrollTo = window.scrollTo;\n window.scrollTo = () => {};\n const scrollIntoView = Element.prototype.scrollIntoView;\n Element.prototype.scrollIntoView = function () {};\n\n // A head module script runs before the runtime at the end of the body.\n if (documentScript) new Function(documentScript)();\n\n const source = STATIC_NAVIGATION_SOURCE.replace(\"import(\", \"__import(\");\n new Function(\"__import\", \"location\", \"fetch\", source)(importIsland, location, fetch);\n\n return {\n requests,\n fullLoads,\n async navigate(href, init) {\n const link = Array.from(document.querySelectorAll(\"a[href]\")).find(\n (a) => a.getAttribute(\"href\") === href,\n );\n if (!link) throw new Error(`renderStaticDocument: no <a href=\"${href}\"> on the page`);\n const done = outcome();\n link.dispatchEvent(new MouseEvent(\"click\", { bubbles: true, cancelable: true, ...init }));\n return await done;\n },\n async back() {\n const done = outcome();\n history.back();\n return await done;\n },\n dispose() {\n (window as unknown as { __gemi_nav?: { d: () => void } }).__gemi_nav?.d();\n window.removeEventListener(\"click\", onClick);\n document.removeEventListener(\"gemi:before-navigate\", onBeforeNavigate);\n document.removeEventListener(\"gemi:page-load\", onPageLoad);\n window.scrollTo = scrollTo;\n Element.prototype.scrollIntoView = scrollIntoView;\n },\n };\n}\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;AAAA,SAAS,WAAW;CAClB,OAAO,WAAW,OAAO,SAAS,OAAO,OAAO,KAAK,IAAI,SAAU,GAAG;EACpE,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;GACzC,IAAI,IAAI,UAAU;GAClB,KAAK,IAAI,KAAK,GAAG,CAAC,CAAC,EAAA,CAAG,eAAe,KAAK,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE;EAC/D;EACA,OAAO;CACT,GAAG,SAAS,MAAM,MAAM,SAAS;AACnC;;;;;;;;ACDA,IAAI;CAEH,SAAU,QAAQ;;;;;;;;CAQjB,OAAO,SAAS;;;;;;CAOhB,OAAO,UAAU;;;;;CAMjB,OAAO,aAAa;AACtB,EAAA,CAAG,WAAW,SAAS,CAAC,EAAE;AAE1B,IAAI,WAAA,QAAA,IAAA,aAAoC,eAAe,SAAU,KAAK;CACpE,OAAO,OAAO,OAAO,GAAG;AAC1B,IAAI,SAAU,KAAK;CACjB,OAAO;AACT;AAEA,SAAS,QAAQ,MAAM,SAAS;CAC9B,IAAI,CAAC,MAAM;EAET,IAAI,OAAO,YAAY,aAAa,QAAQ,KAAK,OAAO;EAExD,IAAI;G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B,WAAY,CAAC;CAGhD,IAAI,gBAAgB,IAAI,SAAS,cAAc,CAAC,CAAC;CAEjD,MAAM,SAAS,yBAAyB,QAAQ,WAAW,WAAW;CACtE,IAAI,SAAS,YAAY,YAAY,SAAS,MAAM,CAAC,CAAC,cAAc,UAAU,KAAK;CAEnF,OAAO;EACL;EACA;EACA,MAAM,SAAS,MAAM,MAAM;GACzB,MAAM,OAAO,MAAM,KAAK,SAAS,iBAAiB,SAAS,CAAC,CAAC,CAAC,MAC3D,MAAM,EAAE,aAAa,MAAM,MAAM,IACpC;GACA,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,qCAAqC,KAAK,eAAe;GACpF,MAAM,OAAO,QAAQ;GACrB,KAAK,cAAc,IAAI,WAAW,SAAS;IAAE,SAAS;IAAM,YAAY;IAAM,GAAG;GAAK,CAAC,CAAC;GACxF,OAAO,MAAM;EACf;EACA,MAAM,OAAO;GACX,MAAM,OAAO,QAAQ;GACrB,QAAQ,KAAK;GACb,OAAO,MAAM;EACf;EACA,UAAU;GACR,OAA0D,YAAY,EAAE;GACxE,OAAO,oBAAoB,SAAS,OAAO;GAC3C,SAAS,oBAAoB,wBAAwB,gBAAgB;GACrE,SAAS,oBAAoB,kBAAkB,UAAU;GACzD,OAAO,WAAW;GAClB,QAAQ,UAAU,iBAAiB;EACrC;CACF;AACF"}
|
package/dist/vitest/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{sa as B,ta as D}from"../chunk-wxyxnbh6.js";import"../chunk-3xzhbkya.js";import"../chunk-6bfj0mbp.js";import{Na as J}from"../chunk-ek0dvbck.js";import"../chunk-2ngdhbz7.js";import"../chunk-k9882kqg.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=1832409EA632F1D064756E2164756E21
|
package/dist/vitest/index.js.map
CHANGED
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import type { Plugin } from \"vite\";\nimport {\n CUSTOM_REQUEST_FILTER,\n customRequestParser,\n} from \"../bun/customRequestParser\";\n\n/**\n * The request-param rewrite, as a Vite plugin, for running an app's routes\n * under vitest.\n *\n * gemi calls a route handler and a controller method with no arguments, and a\n * handler written `async (req: HttpRequest<…>) => …` only gets its request\n * because the build rewrites it to `async (req = new HttpRequest()) => …`, which\n * reads the current request from the request context. The app's build and dev\n * server get that rewrite from `gemi/bun/plugin`. Vitest loads modules through\n * Vite instead, even under `bun --bun vitest`, so without this plugin a route\n * dispatched with `App.fetch` in a test sees `req === undefined`.\n *\n * Same transform, same files (`/http/controllers/` and `/http/routes/`) as the\n * Bun plugin. `enforce: \"pre\"` so it sees the TypeScript annotations before\n * Vite strips them.\n *\n * ```ts\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { gemiRequestPlugin } from \"gemi/vitest\";\n *\n * export default defineConfig({ plugins: [gemiRequestPlugin()] });\n * ```\n */\nexport function gemiRequestPlugin(): Plugin {\n return {\n name: \"gemi-custom-request\",\n enforce: \"pre\",\n async transform(code, id) {\n const path = id.split(\"?\", 1)[0];\n if (path.includes(\"/node_modules/\") || !CUSTOM_REQUEST_FILTER.test(path)) {\n return null;\n }\n return { code: await customRequestParser(code), map: null };\n },\n };\n}\n\n/**\n * gemi's island transform, for an app's `vitest.config.ts`: with it, a test\n * that renders a static view through `App.fetch` sees each\n * `island(() => import(\"./Counter\"))` with the same module key as the build,\n * and a hydrated view renders the component in place instead of lazily.\n *\n * Without it islands still render (the component is loaded with the\n * `import()`), but their keys are unknown.\n *\n * ```ts\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { gemiIslandPlugin, gemiRequestPlugin } from \"gemi/vitest\";\n *\n * export default defineConfig({ plugins: [gemiRequestPlugin(), gemiIslandPlugin()] });\n * ```\n */\nexport { gemiIslandPlugin } from \"../vite/islandPlugin\";\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";yOA8BO,IAAS,JAAiB,HAAW,JAC1C,CAAO,CACL,KAAM,sBACN,QAAS,WACH,UAAS,CAAC,EAAM,EAAI,CACxB,IAAM,EAAO,EAAG,MAAM,IAAK,CAAC,EAAE,GAC9B,GAAI,EAAK,SAAS,gBAAgB,GAAK,CAAC,EAAsB,KAAK,CAAI,EACrE,OAAO,KAET,MAAO,CAAE,KAAM,MAAM,EAAoB,CAAI,EAAG,IAAK,IAAK,EAE9D",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "1832409EA632F1D064756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gemi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.204.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Enes Tufekci <enes@gemijs.dev>",
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
"./ai": "./dist/ai/index.js",
|
|
26
26
|
"./ai/client": "./dist/ai/client/index.js",
|
|
27
27
|
"./ai/voice": "./dist/ai/voice/index.js",
|
|
28
|
+
"./ai/testing": "./dist/ai/testing/index.js",
|
|
28
29
|
"./testing": "./dist/testing/index.js",
|
|
29
30
|
"./app": "./dist/app/index.js",
|
|
30
31
|
"./facades": "./dist/facades/index.js",
|
package/dist/chunk-02s440vh.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{h as ps}from"./chunk-2nw8rf5y.js";import{A as ys,B as Zr,C as ro,i as Se,k as X,l as qs,m as Fs,n as Ws,p as Oo,q as Ko,r as as,s as ws,t as gt,u as Us,v as lo,w as Qt,x as ls,y as Es,z as Ps}from"./chunk-nfbf388w.js";import{D as us}from"./chunk-a1cwr0wh.js";import{E as $o,F as Jr,H as cs,L as dt,P as k}from"./chunk-kmpxda7j.js";import{Q as hs}from"./chunk-2fbsd1b0.js";import{R as Xr}from"./chunk-nkasdjx2.js";import"./chunk-tgbj942e.js";import"./chunk-41fqkygr.js";import{U as Bs}from"./chunk-vee6v6qf.js";import"./chunk-q05648ac.js";import{ba as Hr}from"./chunk-dyb649h3.js";import{ma as ds}from"./chunk-m3xvm2va.js";import{cm as y}from"./chunk-05k9201j.js";var Z=y(($e)=>{Object.defineProperty($e,"__esModule",{value:!0});$e.resolveHttpAuthSchemeConfig=$e.resolveStsAuthConfig=$e.defaultSTSHttpAuthSchemeProvider=$e.defaultSTSHttpAuthSchemeParametersProvider=void 0;var bo=X(),J=$o(),ho=C(),No=async(e,t,r)=>{return{operation:(0,J.getSmithyContext)(t).operation,region:await(0,J.normalizeProvider)(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};$e.defaultSTSHttpAuthSchemeParametersProvider=No;function qo(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:e.region},propertiesExtractor:(t,r)=>({signingProperties:{config:t,context:r}})}}function Fo(e){return{schemeId:"smithy.api#noAuth"}}var Wo=(e)=>{let t=[];switch(e.operation){case"AssumeRoleWithWebIdentity":{t.push(Fo(e));break}default:t.push(qo(e))}return t};$e.defaultSTSHttpAuthSchemeProvider=Wo;var wo=(e)=>Object.assign(e,{stsClientCtor:ho.STSClient});$e.resolveStsAuthConfig=wo;var Uo=(e)=>{let t=$e.resolveStsAuthConfig(e),r=(0,bo.resolveAwsSdkSigV4Config)(t);return Object.assign(r,{authSchemePreference:(0,J.normalizeProvider)(e.authSchemePreference??[])})};$e.resolveHttpAuthSchemeConfig=Uo});var f=y((Ne)=>{Object.defineProperty(Ne,"__esModule",{value:!0});Ne.commonParams=Ne.resolveClientEndpointParameters=void 0;var Lo=(e)=>{return Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,useGlobalEndpoint:e.useGlobalEndpoint??!1,defaultSigningName:"sts"})};Ne.resolveClientEndpointParameters=Lo;Ne.commonParams={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var et=y((Ce)=>{Object.defineProperty(Ce,"__esModule",{value:!0});Ce.ruleSet=void 0;var Ve="required",o="type",n="fn",i="argv",v="ref",Fe=!1,ee=!0,S="booleanEquals",p="stringEquals",ze="sigv4",Be="sts",ge="us-east-1",c="endpoint",We="https://sts.{Region}.{PartitionResult#dnsSuffix}",R="tree",M="error",oe="getAttr",we={[Ve]:!1,[o]:"string"},te={[Ve]:!0,default:!1,[o]:"boolean"},Qe={[v]:"Endpoint"},Ue={[n]:"isSet",[i]:[{[v]:"Region"}]},l={[v]:"Region"},Me={[n]:"aws.partition",[i]:[l],assign:"PartitionResult"},Ye={[v]:"UseFIPS"},He={[v]:"UseDualStack"},P={url:"https://sts.amazonaws.com",properties:{authSchemes:[{name:ze,signingName:Be,signingRegion:ge}]},headers:{}},_={},ke={conditions:[{[n]:p,[i]:[l,"aws-global"]}],[c]:P,[o]:c},Je={[n]:S,[i]:[Ye,!0]},Xe={[n]:S,[i]:[He,!0]},Le={[n]:oe,[i]:[{[v]:"PartitionResult"},"supportsFIPS"]},Ze={[v]:"PartitionResult"},je={[n]:S,[i]:[!0,{[n]:oe,[i]:[Ze,"supportsDualStack"]}]},Ge=[{[n]:"isSet",[i]:[Qe]}],Oe=[Je],Ke=[Xe],Go={version:"1.0",parameters:{Region:we,UseDualStack:te,UseFIPS:te,Endpoint:we,UseGlobalEndpoint:te},rules:[{conditions:[{[n]:S,[i]:[{[v]:"UseGlobalEndpoint"},ee]},{[n]:"not",[i]:Ge},Ue,Me,{[n]:S,[i]:[Ye,Fe]},{[n]:S,[i]:[He,Fe]}],rules:[{conditions:[{[n]:p,[i]:[l,"ap-northeast-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"ap-south-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"ap-southeast-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"ap-southeast-2"]}],endpoint:P,[o]:c},ke,{conditions:[{[n]:p,[i]:[l,"ca-central-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"eu-central-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"eu-north-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"eu-west-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"eu-west-2"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"eu-west-3"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"sa-east-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,ge]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"us-east-2"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"us-west-1"]}],endpoint:P,[o]:c},{conditions:[{[n]:p,[i]:[l,"us-west-2"]}],endpoint:P,[o]:c},{endpoint:{url:We,properties:{authSchemes:[{name:ze,signingName:Be,signingRegion:"{Region}"}]},headers:_},[o]:c}],[o]:R},{conditions:Ge,rules:[{conditions:Oe,error:"Invalid Configuration: FIPS and custom endpoint are not supported",[o]:M},{conditions:Ke,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",[o]:M},{endpoint:{url:Qe,properties:_,headers:_},[o]:c}],[o]:R},{conditions:[Ue],rules:[{conditions:[Me],rules:[{conditions:[Je,Xe],rules:[{conditions:[{[n]:S,[i]:[ee,Le]},je],rules:[{endpoint:{url:"https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:_,headers:_},[o]:c}],[o]:R},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",[o]:M}],[o]:R},{conditions:Oe,rules:[{conditions:[{[n]:S,[i]:[Le,ee]}],rules:[{conditions:[{[n]:p,[i]:[{[n]:oe,[i]:[Ze,"name"]},"aws-us-gov"]}],endpoint:{url:"https://sts.{Region}.amazonaws.com",properties:_,headers:_},[o]:c},{endpoint:{url:"https://sts-fips.{Region}.{PartitionResult#dnsSuffix}",properties:_,headers:_},[o]:c}],[o]:R},{error:"FIPS is enabled but this partition does not support FIPS",[o]:M}],[o]:R},{conditions:Ke,rules:[{conditions:[je],rules:[{endpoint:{url:"https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:_,headers:_},[o]:c}],[o]:R},{error:"DualStack is enabled but this partition does not support DualStack",[o]:M}],[o]:R},ke,{endpoint:{url:We,properties:_,headers:_},[o]:c}],[o]:R}],[o]:R},{error:"Invalid Configuration: Missing Region",[o]:M}]};Ce.ruleSet=Go});var rt=y((tt)=>{Object.defineProperty(tt,"__esModule",{value:!0});tt.defaultEndpointResolver=void 0;var Vo=Ko(),re=Oo(),zo=et(),Bo=new re.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS","UseGlobalEndpoint"]}),go=(e,t={})=>{return Bo.get(e,()=>(0,re.resolveEndpoint)(zo.ruleSet,{endpointParams:e,logger:t.logger}))};tt.defaultEndpointResolver=go;re.customEndpointFunctions.aws=Vo.awsEndpointFunctions});var O=y((ne)=>{Object.defineProperty(ne,"__esModule",{value:!0});ne.STSServiceException=ne.__ServiceException=void 0;var st=k();Object.defineProperty(ne,"__ServiceException",{enumerable:!0,get:function(){return st.ServiceException}});class se extends st.ServiceException{constructor(e){super(e);Object.setPrototypeOf(this,se.prototype)}}ne.STSServiceException=se});var Ee=y((it)=>{Object.defineProperty(it,"__esModule",{value:!0});it.IDPCommunicationErrorException=it.InvalidIdentityTokenException=it.IDPRejectedClaimException=it.RegionDisabledException=it.PackedPolicyTooLargeException=it.MalformedPolicyDocumentException=it.ExpiredTokenException=void 0;var A=O();class ie extends A.STSServiceException{name="ExpiredTokenException";$fault="client";constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e});Object.setPrototypeOf(this,ie.prototype)}}it.ExpiredTokenException=ie;class ce extends A.STSServiceException{name="MalformedPolicyDocumentException";$fault="client";constructor(e){super({name:"MalformedPolicyDocumentException",$fault:"client",...e});Object.setPrototypeOf(this,ce.prototype)}}it.MalformedPolicyDocumentException=ce;class de extends A.STSServiceException{name="PackedPolicyTooLargeException";$fault="client";constructor(e){super({name:"PackedPolicyTooLargeException",$fault:"client",...e});Object.setPrototypeOf(this,de.prototype)}}it.PackedPolicyTooLargeException=de;class ae extends A.STSServiceException{name="RegionDisabledException";$fault="client";constructor(e){super({name:"RegionDisabledException",$fault:"client",...e});Object.setPrototypeOf(this,ae.prototype)}}it.RegionDisabledException=ae;class ue extends A.STSServiceException{name="IDPRejectedClaimException";$fault="client";constructor(e){super({name:"IDPRejectedClaimException",$fault:"client",...e});Object.setPrototypeOf(this,ue.prototype)}}it.IDPRejectedClaimException=ue;class pe extends A.STSServiceException{name="InvalidIdentityTokenException";$fault="client";constructor(e){super({name:"InvalidIdentityTokenException",$fault:"client",...e});Object.setPrototypeOf(this,pe.prototype)}}it.InvalidIdentityTokenException=pe;class le extends A.STSServiceException{name="IDPCommunicationErrorException";$fault="client";constructor(e){super({name:"IDPCommunicationErrorException",$fault:"client",...e});Object.setPrototypeOf(this,le.prototype)}}it.IDPCommunicationErrorException=le});var Te=y((Tt)=>{Object.defineProperty(Tt,"__esModule",{value:!0});Tt.AssumeRoleWithWebIdentity$=Tt.AssumeRole$=Tt.Tag$=Tt.ProvidedContext$=Tt.PolicyDescriptorType$=Tt.Credentials$=Tt.AssumeRoleWithWebIdentityResponse$=Tt.AssumeRoleWithWebIdentityRequest$=Tt.AssumeRoleResponse$=Tt.AssumeRoleRequest$=Tt.AssumedRoleUser$=Tt.errorTypeRegistries=Tt.RegionDisabledException$=Tt.PackedPolicyTooLargeException$=Tt.MalformedPolicyDocumentException$=Tt.InvalidIdentityTokenException$=Tt.IDPRejectedClaimException$=Tt.IDPCommunicationErrorException$=Tt.ExpiredTokenException$=Tt.STSServiceException$=void 0;var Co="Arn",fo="AccessKeyId",er="AssumeRole",tr="AssumedRoleId",or="AssumeRoleRequest",rr="AssumeRoleResponse",Pe="AssumedRoleUser",sr="AssumeRoleWithWebIdentity",nr="AssumeRoleWithWebIdentityRequest",ir="AssumeRoleWithWebIdentityResponse",cr="Audience",ye="Credentials",dr="ContextAssertion",at="DurationSeconds",ar="Expiration",ur="ExternalId",pr="ExpiredTokenException",lr="IDPCommunicationErrorException",Er="IDPRejectedClaimException",Pr="InvalidIdentityTokenException",yr="Key",_r="MalformedPolicyDocumentException",ut="Policy",pt="PolicyArns",Ir="ProviderArn",Rr="ProvidedContexts",Tr="ProvidedContextsListType",Sr="ProvidedContext",vr="PolicyDescriptorType",xr="ProviderId",lt="PackedPolicySize",Dr="PackedPolicyTooLargeException",mr="Provider",Et="RoleArn",Ar="RegionDisabledException",Pt="RoleSessionName",$r="SecretAccessKey",br="SubjectFromWebIdentityToken",_e="SourceIdentity",hr="SerialNumber",Nr="SessionToken",qr="Tags",Fr="TokenCode",Wr="TransitiveTagKeys",wr="Tag",Ur="Value",Mr="WebIdentityToken",kr="arn",Lr="accessKeySecretType",$="awsQueryError",b="client",jr="clientTokenType",h="error",N="httpError",q="message",Gr="policyDescriptorListType",yt="smithy.ts.sdk.synthetic.com.amazonaws.sts",Or="tagListType",d="com.amazonaws.sts",_t=dt(),F=Ee(),Kr=O(),It=_t.TypeRegistry.for(yt);Tt.STSServiceException$=[-3,yt,"STSServiceException",0,[],[]];It.registerError(Tt.STSServiceException$,Kr.STSServiceException);var x=_t.TypeRegistry.for(d);Tt.ExpiredTokenException$=[-3,d,pr,{[$]:["ExpiredTokenException",400],[h]:b,[N]:400},[q],[0]];x.registerError(Tt.ExpiredTokenException$,F.ExpiredTokenException);Tt.IDPCommunicationErrorException$=[-3,d,lr,{[$]:["IDPCommunicationError",400],[h]:b,[N]:400},[q],[0]];x.registerError(Tt.IDPCommunicationErrorException$,F.IDPCommunicationErrorException);Tt.IDPRejectedClaimException$=[-3,d,Er,{[$]:["IDPRejectedClaim",403],[h]:b,[N]:403},[q],[0]];x.registerError(Tt.IDPRejectedClaimException$,F.IDPRejectedClaimException);Tt.InvalidIdentityTokenException$=[-3,d,Pr,{[$]:["InvalidIdentityToken",400],[h]:b,[N]:400},[q],[0]];x.registerError(Tt.InvalidIdentityTokenException$,F.InvalidIdentityTokenException);Tt.MalformedPolicyDocumentException$=[-3,d,_r,{[$]:["MalformedPolicyDocument",400],[h]:b,[N]:400},[q],[0]];x.registerError(Tt.MalformedPolicyDocumentException$,F.MalformedPolicyDocumentException);Tt.PackedPolicyTooLargeException$=[-3,d,Dr,{[$]:["PackedPolicyTooLarge",400],[h]:b,[N]:400},[q],[0]];x.registerError(Tt.PackedPolicyTooLargeException$,F.PackedPolicyTooLargeException);Tt.RegionDisabledException$=[-3,d,Ar,{[$]:["RegionDisabledException",403],[h]:b,[N]:403},[q],[0]];x.registerError(Tt.RegionDisabledException$,F.RegionDisabledException);Tt.errorTypeRegistries=[It,x];var Vr=[0,d,Lr,8,0],zr=[0,d,jr,8,0];Tt.AssumedRoleUser$=[3,d,Pe,0,[tr,Co],[0,0],2];Tt.AssumeRoleRequest$=[3,d,or,0,[Et,Pt,pt,ut,at,qr,Wr,ur,hr,Fr,_e,Rr],[0,0,()=>Rt,0,1,()=>gr,64,0,0,0,0,()=>Br],2];Tt.AssumeRoleResponse$=[3,d,rr,0,[ye,Pe,lt,_e],[[()=>Tt.Credentials$,0],()=>Tt.AssumedRoleUser$,1,0]];Tt.AssumeRoleWithWebIdentityRequest$=[3,d,nr,0,[Et,Pt,Mr,xr,pt,ut,at],[0,0,[()=>zr,0],0,()=>Rt,0,1],3];Tt.AssumeRoleWithWebIdentityResponse$=[3,d,ir,0,[ye,br,Pe,lt,mr,cr,_e],[[()=>Tt.Credentials$,0],0,()=>Tt.AssumedRoleUser$,1,0,0,0]];Tt.Credentials$=[3,d,ye,0,[fo,$r,Nr,ar],[0,[()=>Vr,0],0,4],4];Tt.PolicyDescriptorType$=[3,d,vr,0,[kr],[0]];Tt.ProvidedContext$=[3,d,Sr,0,[Ir,dr],[0,0]];Tt.Tag$=[3,d,wr,0,[yr,Ur],[0,0],2];var Rt=[1,d,Gr,0,()=>Tt.PolicyDescriptorType$],Br=[1,d,Tr,0,()=>Tt.ProvidedContext$],gr=[1,d,Or,0,()=>Tt.Tag$];Tt.AssumeRole$=[9,d,er,0,()=>Tt.AssumeRoleRequest$,()=>Tt.AssumeRoleResponse$];Tt.AssumeRoleWithWebIdentity$=[9,d,sr,0,()=>Tt.AssumeRoleWithWebIdentityRequest$,()=>Tt.AssumeRoleWithWebIdentityResponse$]});var Ot=y((jt)=>{Object.defineProperty(jt,"__esModule",{value:!0});jt.getRuntimeConfig=void 0;var Cr=X(),fr=Zr(),es=Se(),ts=k(),os=Xr(),kt=Jr(),Lt=Hr(),rs=Z(),ss=rt(),ns=Te(),is=(e)=>{return{apiVersion:"2011-06-15",base64Decoder:e?.base64Decoder??kt.fromBase64,base64Encoder:e?.base64Encoder??kt.toBase64,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??ss.defaultEndpointResolver,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??rs.defaultSTSHttpAuthSchemeProvider,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new Cr.AwsSdkSigV4Signer},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new es.NoAuthSigner}],logger:e?.logger??new ts.NoOpLogger,protocol:e?.protocol??fr.AwsQueryProtocol,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.sts",errorTypeRegistries:ns.errorTypeRegistries,xmlNamespace:"https://sts.amazonaws.com/doc/2011-06-15/",version:"2011-06-15",serviceTarget:"AWSSecurityTokenServiceV20110615"},serviceId:e?.serviceId??"STS",urlParser:e?.urlParser??os.parseUrl,utf8Decoder:e?.utf8Decoder??Lt.fromUtf8,utf8Encoder:e?.utf8Encoder??Lt.toUtf8}};jt.getRuntimeConfig=is});var Jt=y((Yt)=>{Object.defineProperty(Yt,"__esModule",{value:!0});Yt.getRuntimeConfig=void 0;var _s=ds(),Is=_s.__importDefault(ps()),ve=X(),Kt=ls(),K=gt(),Rs=Se(),Ts=Es(),Vt=Qt(),W=us(),zt=cs(),Bt=k(),Ss=Ps(),vs=ys(),xs=as(),Ds=Ot(),ms=(e)=>{(0,Bt.emitWarningIfUnsupportedVersion)(process.version);let t=(0,vs.resolveDefaultsModeConfig)(e),r=()=>t().then(Bt.loadConfigsForDefaultMode),a=(0,Ds.getRuntimeConfig)(e);(0,ve.emitWarningIfUnsupportedVersion)(process.version);let s={profile:e?.profile,logger:a.logger};return{...a,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??(0,W.loadConfig)(ve.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,s),bodyLengthChecker:e?.bodyLengthChecker??Ss.calculateBodyLength,defaultUserAgentProvider:e?.defaultUserAgentProvider??(0,Kt.createDefaultUserAgentProvider)({serviceId:a.serviceId,clientVersion:Is.default.version}),httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(E)=>E.getIdentityProvider("aws.auth#sigv4")||(async(u)=>await e.credentialDefaultProvider(u?.__config||{})()),signer:new ve.AwsSdkSigV4Signer},{schemeId:"smithy.api#noAuth",identityProvider:(E)=>E.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new Rs.NoAuthSigner}],maxAttempts:e?.maxAttempts??(0,W.loadConfig)(Vt.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,e),region:e?.region??(0,W.loadConfig)(K.NODE_REGION_CONFIG_OPTIONS,{...K.NODE_REGION_CONFIG_FILE_OPTIONS,...s}),requestHandler:zt.NodeHttpHandler.create(e?.requestHandler??r),retryMode:e?.retryMode??(0,W.loadConfig)({...Vt.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await r()).retryMode||xs.DEFAULT_RETRY_MODE},e),sha256:e?.sha256??Ts.Hash.bind(null,"sha256"),streamCollector:e?.streamCollector??zt.streamCollector,useDualstackEndpoint:e?.useDualstackEndpoint??(0,W.loadConfig)(K.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,s),useFipsEndpoint:e?.useFipsEndpoint??(0,W.loadConfig)(K.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,s),userAgentAppId:e?.userAgentAppId??(0,W.loadConfig)(Kt.NODE_APP_ID_CONFIG_OPTIONS,s)}};Yt.getRuntimeConfig=ms});var Ct=y((Xt)=>{Object.defineProperty(Xt,"__esModule",{value:!0});Xt.resolveHttpAuthRuntimeConfig=Xt.getHttpAuthExtensionConfiguration=void 0;var As=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:r,credentials:a}=e;return{setHttpAuthScheme(s){let E=t.findIndex((u)=>u.schemeId===s.schemeId);if(E===-1)t.push(s);else t.splice(E,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){r=s},httpAuthSchemeProvider(){return r},setCredentials(s){a=s},credentials(){return a}}};Xt.getHttpAuthExtensionConfiguration=As;var $s=(e)=>{return{httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}};Xt.resolveHttpAuthRuntimeConfig=$s});var io=y((so)=>{Object.defineProperty(so,"__esModule",{value:!0});so.resolveRuntimeExtensions=void 0;var ft=ro(),eo=hs(),to=k(),oo=Ct(),Ns=(e,t)=>{let r=Object.assign((0,ft.getAwsRegionExtensionConfiguration)(e),(0,to.getDefaultExtensionConfiguration)(e),(0,eo.getHttpHandlerExtensionConfiguration)(e),(0,oo.getHttpAuthExtensionConfiguration)(e));return t.forEach((a)=>a.configure(r)),Object.assign(e,(0,ft.resolveAwsRegionExtensionConfiguration)(r),(0,to.resolveDefaultRuntimeConfig)(r),(0,eo.resolveHttpHandlerRuntimeConfig)(r),(0,oo.resolveHttpAuthRuntimeConfig)(r))};so.resolveRuntimeExtensions=Ns});var C=y((De)=>{Object.defineProperty(De,"__esModule",{value:!0});De.STSClient=De.__Client=void 0;var co=qs(),Ms=Fs(),ks=Ws(),ao=ws(),Ls=gt(),xe=Se(),js=dt(),Gs=Us(),Os=lo(),uo=Qt(),Eo=k();Object.defineProperty(De,"__Client",{enumerable:!0,get:function(){return Eo.Client}});var po=Z(),Ks=f(),Vs=Jt(),zs=io();class Po extends Eo.Client{config;constructor(...[e]){let t=(0,Vs.getRuntimeConfig)(e||{});super(t);this.initConfig=t;let r=(0,Ks.resolveClientEndpointParameters)(t),a=(0,ao.resolveUserAgentConfig)(r),s=(0,uo.resolveRetryConfig)(a),E=(0,Ls.resolveRegionConfig)(s),u=(0,co.resolveHostHeaderConfig)(E),T=(0,Os.resolveEndpointConfig)(u),D=(0,po.resolveHttpAuthSchemeConfig)(T),m=(0,zs.resolveRuntimeExtensions)(D,e?.extensions||[]);this.config=m,this.middlewareStack.use((0,js.getSchemaSerdePlugin)(this.config)),this.middlewareStack.use((0,ao.getUserAgentPlugin)(this.config)),this.middlewareStack.use((0,uo.getRetryPlugin)(this.config)),this.middlewareStack.use((0,Gs.getContentLengthPlugin)(this.config)),this.middlewareStack.use((0,co.getHostHeaderPlugin)(this.config)),this.middlewareStack.use((0,Ms.getLoggerPlugin)(this.config)),this.middlewareStack.use((0,ks.getRecursionDetectionPlugin)(this.config)),this.middlewareStack.use((0,xe.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config,{httpAuthSchemeParametersProvider:po.defaultSTSHttpAuthSchemeParametersProvider,identityProviderConfigProvider:async(U)=>new xe.DefaultIdentityProviderConfig({"aws.auth#sigv4":U.credentials})})),this.middlewareStack.use((0,xe.getHttpSigningPlugin)(this.config))}destroy(){super.destroy()}}De.STSClient=Po});var nn=y((I)=>{var w=C(),z=k(),_o=lo(),Io=f(),L=Te(),V=Ee(),me=Bs(),gs=ro(),Qs=O();class B extends z.Command.classBuilder().ep(Io.commonParams).m(function(e,t,r,a){return[_o.getEndpointPlugin(r,e.getEndpointParameterInstructions())]}).s("AWSSecurityTokenServiceV20110615","AssumeRole",{}).n("STSClient","AssumeRoleCommand").sc(L.AssumeRole$).build(){}class g extends z.Command.classBuilder().ep(Io.commonParams).m(function(e,t,r,a){return[_o.getEndpointPlugin(r,e.getEndpointParameterInstructions())]}).s("AWSSecurityTokenServiceV20110615","AssumeRoleWithWebIdentity",{}).n("STSClient","AssumeRoleWithWebIdentityCommand").sc(L.AssumeRoleWithWebIdentity$).build(){}var Ys={AssumeRoleCommand:B,AssumeRoleWithWebIdentityCommand:g};class Ae extends w.STSClient{}z.createAggregatedClient(Ys,Ae);var Ro=(e)=>{if(typeof e?.Arn==="string"){let t=e.Arn.split(":");if(t.length>4&&t[4]!=="")return t[4]}return},To=async(e,t,r,a={})=>{let s=typeof e==="function"?await e():e,E=typeof t==="function"?await t():t,u="",T=s??E??(u=await gs.stsRegionDefaultResolver(a)());return r?.debug?.("@aws-sdk/client-sts::resolveRegion","accepting first of:",`${s} (credential provider clientConfig)`,`${E} (contextual client)`,`${u} (STS default: AWS_REGION, profile region, or us-east-1)`),T},Hs=(e,t)=>{let r,a;return async(s,E)=>{if(a=s,!r){let{logger:U=e?.parentClientConfig?.logger,profile:j=e?.parentClientConfig?.profile,region:Q,requestHandler:G=e?.parentClientConfig?.requestHandler,credentialProviderLogger:Y,userAgentAppId:H=e?.parentClientConfig?.userAgentAppId}=e,mo=await To(Q,e?.parentClientConfig?.region,Y,{logger:U,profile:j}),Ao=!So(G);r=new t({...e,userAgentAppId:H,profile:j,credentialDefaultProvider:()=>async()=>a,region:mo,requestHandler:Ao?G:void 0,logger:U})}let{Credentials:u,AssumedRoleUser:T}=await r.send(new B(E));if(!u||!u.AccessKeyId||!u.SecretAccessKey)throw Error(`Invalid response from STS.assumeRole call with role ${E.RoleArn}`);let D=Ro(T),m={accessKeyId:u.AccessKeyId,secretAccessKey:u.SecretAccessKey,sessionToken:u.SessionToken,expiration:u.Expiration,...u.CredentialScope&&{credentialScope:u.CredentialScope},...D&&{accountId:D}};return me.setCredentialFeature(m,"CREDENTIALS_STS_ASSUME_ROLE","i"),m}},Js=(e,t)=>{let r;return async(a)=>{if(!r){let{logger:D=e?.parentClientConfig?.logger,profile:m=e?.parentClientConfig?.profile,region:U,requestHandler:j=e?.parentClientConfig?.requestHandler,credentialProviderLogger:Q,userAgentAppId:G=e?.parentClientConfig?.userAgentAppId}=e,Y=await To(U,e?.parentClientConfig?.region,Q,{logger:D,profile:m}),H=!So(j);r=new t({...e,userAgentAppId:G,profile:m,region:Y,requestHandler:H?j:void 0,logger:D})}let{Credentials:s,AssumedRoleUser:E}=await r.send(new g(a));if(!s||!s.AccessKeyId||!s.SecretAccessKey)throw Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${a.RoleArn}`);let u=Ro(E),T={accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken,expiration:s.Expiration,...s.CredentialScope&&{credentialScope:s.CredentialScope},...u&&{accountId:u}};if(u)me.setCredentialFeature(T,"RESOLVED_ACCOUNT_ID","T");return me.setCredentialFeature(T,"CREDENTIALS_STS_ASSUME_ROLE_WEB_ID","k"),T}},So=(e)=>{return e?.metadata?.handlerProtocol==="h2"},vo=(e,t)=>{if(!t)return e;else return class extends e{constructor(a){super(a);for(let s of t)this.middlewareStack.use(s)}}},xo=(e={},t)=>Hs(e,vo(w.STSClient,t)),Do=(e={},t)=>Js(e,vo(w.STSClient,t)),Xs=(e)=>(t)=>e({roleAssumer:xo(t),roleAssumerWithWebIdentity:Do(t),...t});I.$Command=z.Command;I.STSServiceException=Qs.STSServiceException;I.AssumeRoleCommand=B;I.AssumeRoleWithWebIdentityCommand=g;I.STS=Ae;I.decorateDefaultCredentialProvider=Xs;I.getDefaultRoleAssumer=xo;I.getDefaultRoleAssumerWithWebIdentity=Do;Object.prototype.hasOwnProperty.call(w,"__proto__")&&!Object.prototype.hasOwnProperty.call(I,"__proto__")&&Object.defineProperty(I,"__proto__",{enumerable:!0,value:w.__proto__});Object.keys(w).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(I,e))I[e]=w[e]});Object.prototype.hasOwnProperty.call(L,"__proto__")&&!Object.prototype.hasOwnProperty.call(I,"__proto__")&&Object.defineProperty(I,"__proto__",{enumerable:!0,value:L.__proto__});Object.keys(L).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(I,e))I[e]=L[e]});Object.prototype.hasOwnProperty.call(V,"__proto__")&&!Object.prototype.hasOwnProperty.call(I,"__proto__")&&Object.defineProperty(I,"__proto__",{enumerable:!0,value:V.__proto__});Object.keys(V).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(I,e))I[e]=V[e]})});export default nn();
|
|
3
|
-
|
|
4
|
-
//# debugId=409F03BD85FE50FD64756E2164756E21
|